Serving Multiple Clients

I wonder if it is really possible for a simple server program using server socket can handle multiple clients at the same time simultaneously? I am creating a server program that needs to handle multiple clients. With the same port number. But the problem is the program will only serve one client at a time, and in order for it to serve the other client, the first connection have to be terminated.

Here is the code:

try{

        ServerSocket server = new ServerSocket(PORT);
        System.out.println("Server Running...");
        while(true){
            Socket socket = server.accept();
            System.out.println("Connection from:"+socket.getInetAddress());
            Scanner in = new Scanner (socket.getInputStream());
            PrintWriter output = new PrintWriter(socket.getOutputStream());
        }
    }catch(Exception e){
        System.out.println(e);
    }

Is there any possible java code that will be added here in order to for the program to serve multiple clients simultaneously?

Jon Skeet
people
quotationmark

The code you've posted doesn't actually do anything with the client connection, which makes it hard to help you. But yes, it's entirely possible for a server to handle multiple concurrent connections.

My guess is that the problem is that you're doing everything on a single thread, with synchronous IO. That means that while you're waiting for data from the existing client, you're not accepting new connections. Typically a server takes one of two approaches:

  • Starting a thread (or reusing one from a thread pool) when it accepts a connection, and letting that thread deal with that connection exclusive.
  • Using asynchronous IO to do everything on a single thread (or a small number of threads).

The latter approach can be more efficient, but it also significantly more complicated. I'd suggest you use a "thread per connection" approach to start with. While you're experimenting, you can simply start a brand new Thread each time a client connects - but for production use, you'd use an ExecutorService or something similar, in order to reuse threads.

Note that depending on what kind of server you're building, all of this may well be done for you in third party libraries.

people

See more on this question at Stackoverflow