sockets

A socket is one endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent to.

Single thread client-server architecture using sockets

Server code

public class Server {
    public static void main(String[] args) {
        int port = 12345;

        // Create a server socket endpoint for server
        try (ServerSocket serverSocket = new ServerSocket(port)) {
            System.out.println("Server is listening for incoming connections...");

            while (true) {
                Socket clientSocket = serverSocket.accept(); // This waits for a client to connect to port server is on
                System.out.println("Client connected: " + clientSocket.getInetAddress());

                // Create input stream to receive message from client
                BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                // Create output stream to echo message back to client
                PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);

                String message;
                while ((message = in.readLine()) != null) {
                    System.out.println("Received: " + message);
                    out.println(" SERVER ECHOS BACK : " + message);  // Echo the message back to the client
                }

                clientSocket.close();
                System.out.println("Client disconnected.");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Client code

However this a client-server application created like this can only have one single client connected to a server ...

This is because socket operations, such as reading and writing data, are often blocking, meaning they will pause the execution of the program until data is sent or received... (one thread for one client)

So in order to have a application that has multiple client connected to a server , we have to use multithreading.

Multi-threaded client-server architecture using sockets

A new thread is created whenever a client tries to connect to the server

ClientHandler creates the functionality of the thread created for the client in run()

Last updated