Socket
class represents a TCP client socket.
The following code shows how to create a TCP client socket:
// Create Socket for 192.168.1.2 at port 1234 Socket socket = new Socket("192.168.1.2", 1234);
The following code shows how to create an unbound client socket, bind it, and connect it.
Socket socket = new Socket(); socket.bind(new InetSocketAddress("localhost", 1234)); socket.connect(new InetSocketAddress("localhost", 1234));
After connecting a Socket object, we can use its input and output streams using the getInputStream() and getOutputStream() methods, respectively.
The following code shows an Echo Client Based on TCP Sockets.
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.Socket; // ww w . jav a2 s . c o m public class Main { public static void main(String[] args) throws Exception { Socket socket = new Socket("localhost", 12900); System.out.println("Started client socket at " + socket.getLocalSocketAddress()); BufferedReader socketReader = new BufferedReader(new InputStreamReader( socket.getInputStream())); BufferedWriter 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(); // Print a blank line System.out.print(promptMsg); } socket.close(); } }