EchoServerMulti.java


Below is the syntax highlighted version of EchoServerMulti.java from §8.4 Operating Systems.


/******************************************************************************
 *  Compilation:  javac EchoServerMulti.java EchoConnection.java
 *  Execution:    java EchoServerMulti
 *  Dependencies: EchoConnection.java In.java Out.java
 *
 *  Runs an echo server on port 4444. Each client connection is handled
 *  in a separate thread, so multiple clients can use the server at once.
 *  Works with EchoClient.java.
 *
 ******************************************************************************/

import java.net.Socket;
import java.net.ServerSocket;

public class EchoServerMulti {

    public static void main(String[] args) throws Exception {

        // create server socket
        int port = 4444;
        ServerSocket serverSocket = new ServerSocket(port);
        System.err.println("Started server on port " + port);

        // repeatedly wait for connections
        while (true) {

            // wait for next client connection request
            Socket clientSocket = serverSocket.accept();
            System.err.println("Accepted connection from client");

            // handle this client in a separate thread
            EchoConnection connection = new EchoConnection(clientSocket);
            connection.start();
        }
    }
}


Copyright © 2000–2025, Robert Sedgewick and Kevin Wayne.
Last updated: Fri Nov 13 05:42:33 PM EST 2026.