YouTip LogoYouTip

Net Multisoc

Java Example – Implementing a Multi-threaded Server Program with Sockets

Java Examples Java Examples

In Java, you can implement a multi-threaded server program by using ServerSocket to listen for client connections. Whenever a new client connects, a new thread is started to handle that connection. Below is an example code demonstrating how to use Java Sockets to implement a multi-threaded server program.

Server-side Code

First, we create a server-side program that listens on a specified port and starts a new thread for each client connection to handle communication.

MultiThreadedServer.java File

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

public class MultiThreadedServer {
    public static void main(String[] args) {
        int port = 12345;
        try (ServerSocket serverSocket = new ServerSocket(port)) {
            System.out.println("Server started, waiting for client connections...");
            while (true) {
                Socket clientSocket = serverSocket.accept();
                System.out.println("Client connected: " + clientSocket.getInetAddress().getHostAddress());
                ClientHandler clientHandler = new ClientHandler(clientSocket);
                new Thread(clientHandler).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

class ClientHandler implements Runnable {
    private Socket clientSocket;

    public ClientHandler(Socket socket) {
        this.clientSocket = socket;
    }

    @Override
    public void run() {
        try (
            InputStream input = clientSocket.getInputStream();
            OutputStream output = clientSocket.getOutputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(input));
            PrintWriter writer = new PrintWriter(output, true)
        ) {
            String clientMessage;
            while ((clientMessage = reader.readLine()) != null) {
                System.out.println("Received client message: " + clientMessage);
                writer.println("Server response: " + clientMessage);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Client Code

The client code is used to connect to the server and send messages. You can create multiple clients to test the server's multi-threaded handling capability.

Client.java File Code:

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

public class Client {
    public static void main(String[] args) {
        String serverAddress = "localhost";
        int port = 12345; // Server port

        try (Socket socket = new Socket(serverAddress, port)) {
            System.out.println("Connected to server");

            OutputStream output = socket.getOutputStream();
            PrintWriter writer = new PrintWriter(output, true);

            InputStream input = socket.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(input));

            BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in));
            String userInput;

            while ((userInput = consoleReader.readLine()) != null) {
                writer.println(userInput);
                String serverResponse = reader.readLine();
                System.out.println("Server response: " + serverResponse);
            }
        } catch (UnknownHostException e) {
            System.err.println("Unknown host: " + serverAddress);
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("Could not get I/O connection to: " + serverAddress);
            e.printStackTrace();
        }
    }
}

Running Steps

  1. Run the Server:
    • Compile and run the MultiThreadedServer class.
    • The server will start and listen for client connections on the specified port.
  2. Run the Client:
    • Compile and run multiple instances of the Client class to simulate multiple clients connecting to the server.
    • In the client console, enter messages. The client will send the message to the server, and the server will respond with the same message.

Explanation

  • ServerSocket: The socket used on the server side to listen for client connections.
  • Socket: The communication channel between the client and the server.
  • ClientHandler: The thread class that handles each client connection.
  • BufferedReader and PrintWriter: Used for reading from and writing to data streams.

This implementation ensures that the server can handle multiple client connections simultaneously without being blocked by a long-running operation from one client, which would otherwise block requests from other clients.

Compiling the Code

Open a terminal or command prompt, navigate to the directory containing the Java files above, and compile the code:

javac MultiThreadedServer.java Client.java

After compilation, first run the server program. The server will start and begin listening on port 12345.

java MultiThreadedServer

You will see the server output:

Server started, waiting for client connections...

Open another terminal or command prompt window and run the client program. You can run multiple client instances to test multi-threaded handling.

java Client

You will see the client output:

Connected to server

Then, you can enter messages in the client console, for example:

Hello Server

The server will respond:

Server response: Hello Server

The server-side output will display:

Client connected: 127.0.0.1
Received client message: Hello Server

Java Examples Java Examples

← Cpp Data EncapsulationNet Connected β†’