Java Examples - Socket Implementation of a Multithreaded Server Program

Java Examples

In Java, implementing a multithreaded server program can be done by usingServerSocketto 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 Socket to implement a multithreaded 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; //Define the server port try (ServerSocket serverSocket = new ServerSocket(port)) { System.out.println("Server started, waiting for client connections..."); while (true) { Socket clientSocket = serverSocket.accept(); //Accept client connection System.out.println("Client connected:" + clientSocket.getInetAddress().getHostAddress()); //Start a new thread for each client connection 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); //Send the response message to the client } } catch (IOException e) { e.printStackTrace(); } finally { try { clientSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } }

Client-side code

The client code is used to connect to the server and send messages. You can create multiple clients to test the server's multithreading 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("Unable to get I/O connection to: " + serverAddress);
            e.printStackTrace();
        }
    }
}

Running steps

  1. Run the server side:

    • Compile and runMultiThreadedServerclass.
    • The server will start and listen for client connections on the specified port.
  2. Run the client:

    • Compile and run multipleClientclass instances to simulate multiple clients connecting to the server.
    • Enter a message in the client console. 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.
  • BufferedReaderandPrintWriter: Used for reading and writing data streams.

This implementation ensures that the server can handle multiple client connections simultaneously without one client's long-running operation blocking other clients' requests.

Compile the code

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

javac MultiThreadedServer.java Client.java

After compilation is complete, 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 connection...

Open another terminal or command prompt window and run the client program. You can run multiple client instances to test multithreaded processing.

java Client

You will see the client output:

Connected to server

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

Hello Server

The server will respond:

服务器回应: Hello Server

The server-side output will display:

客户端已连接: 127.0.0.1
收到客户端消息: Hello Server

Java Examples

Other Extensions