Java Socket create

Introduction

The following snippet of code shows how to create a TCP client socket:

// Create a client socket, which is bound to the localhost at any available port 
// connected to remote IP 192.168.1.2 at port 3456 
Socket socket = new Socket("192.168.1.2", 3456); 

// Create an unbound client socket. bind it, and connect it. 
Socket socket = new Socket(); 
socket.bind(new InetSocketAddress("localhost", 14101)); 
socket.connect(new InetSocketAddress("localhost", 12900)); 

An Echo Client Based on TCP Sockets

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;

public class Main {
  public static void main(String[] args) {
    Socket socket = null;/*from ww w  .ja va  2 s .co  m*/
    BufferedReader socketReader = null;
    BufferedWriter socketWriter = null;
    try {
      // Create a socket that will connect to local host at port 12900.
      // the server must also be running at local host and 12900.
      socket = new Socket("localhost", 12900);

      System.out.println("Started client socket at " + socket.getLocalSocketAddress());

      socketReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
      socketWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

      BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in));

      String promptMsg = "Please enter a message (Bye to quit):";
      String outMsg = null;

      System.out.print(promptMsg);
      while ((outMsg = consoleReader.readLine()) != null) {
        if (outMsg.equalsIgnoreCase("bye")) {
          break;
        }
        // Add a new line to the message to the server,
        // because the server reads one line at a time.
        socketWriter.write(outMsg);
        socketWriter.write("\n");
        socketWriter.flush();

        // Read and display the message from the server
        String inMsg = socketReader.readLine();
        System.out.println("Server: " + inMsg);

        System.out.println(); 
        System.out.print(promptMsg);
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      // Finally close the socket
      if (socket != null) {
        try {
          socket.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }
}



PreviousNext

Related