Creating a Server in Java

Java Server with ServerSocket

Creating a Basic Server in Java Using ServerSocket

In this post, we’ll explore how to create a basic server in Java using the ServerSocket class, handle client connections, and introduce multi-threading to manage multiple clients concurrently.

1. Writing a Basic Server Using ServerSocket

The ServerSocket class in Java is used to create a server that listens for incoming client connections. Here, we’ll write a simple server that accepts a connection from a client and responds with a message.

Basic Server


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

public class BasicServer {
    public static void main(String[] args) {
        int port = 8080; // Server port number
        try (ServerSocket serverSocket = new ServerSocket(port)) {
            System.out.println("Server is listening on port " + port);

            while (true) {
                Socket socket = serverSocket.accept(); // Accept a client connection
                System.out.println("New client connected");

                // Get input and output streams
                InputStream input = socket.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                OutputStream output = socket.getOutputStream();
                PrintWriter writer = new PrintWriter(output, true);

                // Read client message
                String clientMessage = reader.readLine();
                System.out.println("Client says: " + clientMessage);

                // Send response to client
                writer.println("Hello, Client!");

                // Close the socket
                socket.close();
            }
        } catch (IOException e) {
            System.out.println("Server exception: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

2. Handling Client Connections

In the example above, the server can handle only one client at a time. To manage multiple clients, we need to handle each client connection in a separate thread.

3. Multi-threading Basics for Handling Multiple Clients

To support multiple clients simultaneously, we can create a new thread for each client connection. This approach ensures that the server remains responsive and can handle multiple connections concurrently.

Multi-threaded Server


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

public class MultiThreadedServer {
    public static void main(String[] args) {
        int port = 8080; // Server port number
        try (ServerSocket serverSocket = new ServerSocket(port)) {
            System.out.println("Server is listening on port " + port);

            while (true) {
                Socket socket = serverSocket.accept(); // Accept a client connection
                System.out.println("New client connected");

                // Create a new thread for the client
                new ClientHandler(socket).start();
            }
        } catch (IOException e) {
            System.out.println("Server exception: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

class ClientHandler extends Thread {
    private Socket socket;

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

    public void run() {
        try {
            // Get input and output streams
            InputStream input = socket.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(input));
            OutputStream output = socket.getOutputStream();
            PrintWriter writer = new PrintWriter(output, true);

            // Read client message
            String clientMessage;
            while ((clientMessage = reader.readLine()) != null) {
                System.out.println("Client says: " + clientMessage);
                // Send response to client
                writer.println("Hello, Client!");
            }

            // Close the socket
            socket.close();
        } catch (IOException e) {
            System.out.println("Server exception: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

In the MultiThreadedServer class, we create a new thread for each client connection by instantiating the ClientHandler class, which extends Thread. The ClientHandler class is responsible for managing the communication with the client.

Within the run method of the ClientHandler class, we handle the client's requests and send responses back. This method continues to read messages from the client until the client disconnects.

Conclusion

In this post, we’ve demonstrated how to create a basic server in Java using the ServerSocket class. We also highlighted how to handle client connections and introduced multi-threading to manage multiple clients concurrently. By using multi-threading, your server can handle numerous client connections simultaneously, making it more robust and scalable. Happy coding!