Java Network Tutorial - 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;
/*  w ww .j a  v a  2 s .  co  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 a v a 2 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();
    }

  }
}