Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Java TCP server


May 10, 2021 Java


Table of contents


Java Web Tutorial - Java TCP Server


ServerSocket class represents a TCP server socket in Java.

ServerSocket object can accept connection requests from remote clients.

We can use the no-args constructor to create an unbound server socket and use its bind() method to bind it to local ports and local IP addresses.

Example

The following code shows how to create a server socket:

import java.net.InetSocketAddress;
import java.net.ServerSocket;

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 waiting queue size is 50.

The default value for the local IP address is the wildcard address, which is all the IP addresses of the server computer.

ServerSocket(int port)
ServerSocket(int port, int waitQueueSize)
ServerSocket(int port, int waitQueueSize,  InetAddress  bindAddr)

You can combine socket creation and binding steps into a single statement.

The following code shows how to create a server socket on port 12900, where 100 is the waiting queue size and is returned at the localhost 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 execution until a request from a remote client reaches its waiting queue.


The following code calls on ServerSocket will wait  for a  new remote  connection request.
Socket activeSocket = serverSocket.accept();

The Socket class contains two getInputStream() getOutputStream() reading and writing sockets to the connection.

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();

Finally, use the socket's close() method to close the connection. Turning off sockets also closes their 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;

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();
    }

  }
}