Create Single-Threaded TCP Echo Server and Client using Java

TCP is a communication protocol that allows exchange data between devices in a network. TCP is a connection-oriented protocol. This means that communication between devices is reliable and guarantees that all data will be properly send and received. Echo server is a server that receives data from a client and sends back identical copy of the data to a client.

This tutorial shows how to create a single-threaded TCP echo server and client using Java. A single-threaded server means that it accepts only one client connection at a time.

TCP echo server is implemented in the TcpEchoServer class. In the main method an instance of ServerSocket class is created to listen connections on specified port.

We use an infinite while loop to accept connection from a client infinity times. The accept method is invoked which blocks code execution until it receives a connection from a client. When connection is established, the accept method returns an instance of a Socket class. We get the input and output streams of a client socket. The try-with resources statement is used to ensure that opened resources will be automatically closed at the end of the statement.

The readLine method is used to read received data from the client line by line. Data is printed to the standard output and sent back to the client. Reading process will be finished when “Bye” message is received.

TcpEchoServer.java

import java.io.*;
import java.net.*;

public class TcpEchoServer
{
    private final static int PORT = 8080;

    public static void main(String[] args) throws IOException
    {
        ServerSocket serverSocket = new ServerSocket(PORT);

        System.out.println("Listening on port " + PORT);

        while (true) {
            try (Socket socket = serverSocket.accept();
                 InputStreamReader isr = new InputStreamReader(socket.getInputStream());
                 BufferedReader in = new BufferedReader(isr);
                 PrintWriter out = new PrintWriter(socket.getOutputStream(), true)
            ) {
                System.out.println("Connection accepted");

                String line;
                while ((line = in.readLine()) != null) {
                    System.out.println("Server received: " + line + ". Sending to client");
                    out.println(line);

                    if (line.equals("Bye")) {
                        break;
                    }
                }
            }
        }
    }
}

TCP echo client is implemented in the TcpEchoClient class. In the main method an instance of Socket class is created to connect to the server on specified port. We use localhost because our server and client are running on the same machine.

When connection is established client send data to the server. After that, client reads received data from the server line by line and prints to the standard output.

TcpEchoClient.java

import java.io.*;
import java.net.*;

public class TcpEchoClient
{
    private final static String HOSTNAME = "localhost";
    private final static int PORT = 8080;

    public static void main(String[] args) throws IOException
    {
        try (Socket clientSocket = new Socket(HOSTNAME, PORT);
             InputStreamReader isr = new InputStreamReader(clientSocket.getInputStream());
             BufferedReader in = new BufferedReader(isr);
             PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)
        ) {
            System.out.println("Connected to " + HOSTNAME + " on port " + PORT);

            String data = "Hello\nBye";

            System.out.println("Sending to server:\n" + data);
            out.println(data);

            String line;
            while ((line = in.readLine()) != null) {
                System.out.println("Client received: " + line);
            }
        }
    }
}

First we start TCP echo server and then the client. The following messages are printed to the standard output in the server:

Listening on port 8080
Connection accepted
Server received: Hello. Sending to client
Server received: Bye. Sending to client

Client prints the following messages:

Connected to localhost on port 8080
Sending to server:
Hello
Bye
Client received: Hello
Client received: Bye

Leave a Comment

Your email address will not be published. Required fields are marked *