Java TCP Server
An object of the ServerSocket
class represents a TCP server socket in Java.
A ServerSocket
object can accept a connection request from a remote client.
We can use the no-args constructor to create an unbound server socket and use its bind() method to bind it to a local port and a local IP address.
Example
The following code shows how to create a server socket:
import java.net.InetSocketAddress; import java.net.ServerSocket; //www . j a v a2s .c o m public class Main { public static void main(String[] argv) throws Exception { // Create an unbound server socket ServerSocket serverSocket = new ServerSocket(); // Create a socket address object InetSocketAddress endPoint = new InetSocketAddress("localhost", 12900); // Set the wait queue size to 100 int waitQueueSize = 100; // Bind the server socket to localhost and at port 12900 with // a wait queue size of 100 serverSocket.bind(endPoint, waitQueueSize); } }
Example 2
You can combine create, bind, and listen operations in one step by using any of the following constructors.
The default value for the wait queue size is 50.
The default value for a local IP address is the wild-card address, which means all IP addresses of the server machine.
ServerSocket(int port) ServerSocket(int port, int waitQueueSize) ServerSocket(int port, int waitQueueSize, InetAddress bindAddr)
You can combine the socket creation and bind steps into one statement.
The following code shows how to create a server socket at port 12900, with 100 as the wait queue size and at the localhost loopback address.
ServerSocket serverSocket = new ServerSocket(12900, 100, InetAddress.getByName("localhost"));
To accept a remote connection request, call the accept()
method on the server socket.
The accept() method call blocks the execution until a request from a remote client arrives in its wait queue.
The following code calls on ServerSocket will wait for a new remote connection request.
Socket activeSocket = serverSocket.accept();
The Socket class contains two methods getInputStream()
and getOutputStream()
for reading and writing to the connected socket.
BufferedReader br = new BufferedReader(new InputStreamReader(activeSocket.getInputStream())); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(activeSocket.getOutputStream())); String s = br.readLine(); bw.write('hello"); bw.flush();
At the end, close the connection using the socket's close() method. Closing the socket also closes its input and output streams.
activeSocket.close();
The following code shows how to create a server socket.
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; // ww w . j av a2 s . c om public class Main { public static void main(String[] args) throws Exception { ServerSocket serverSocket = new ServerSocket(12900, 100, InetAddress.getByName("localhost")); System.out.println("Server started at: " + serverSocket); while (true) { System.out.println("Waiting for a connection..."); final Socket activeSocket = serverSocket.accept(); System.out.println("Received a connection from " + activeSocket); Runnable runnable = () -> handleClientRequest(activeSocket); new Thread(runnable).start(); // start a new thread } } public static void handleClientRequest(Socket socket) { try{ BufferedReader socketReader = null; BufferedWriter socketWriter = null; socketReader = new BufferedReader(new InputStreamReader( socket.getInputStream())); socketWriter = new BufferedWriter(new OutputStreamWriter( socket.getOutputStream())); String inMsg = null; while ((inMsg = socketReader.readLine()) != null) { System.out.println("Received from client: " + inMsg); String outMsg = inMsg; socketWriter.write(outMsg); socketWriter.write("\n"); socketWriter.flush(); } socket.close(); }catch(Exception e){ e.printStackTrace(); } } }
Java Network TCP Client Socket
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.
Example
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; /* w w w . j ava2 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(); } }