Search code examples
javamultithreadingsocketsobjectoutputstreamobjectinputstream

Communicating with multiple clients - Java Server


I have implemented a small Java chatroom program, where clients can communicate with the server. Although multiple clients won't work - I believe this is because a client reserves a socket while connected? Is there a simple way to add multiple client functionality? Thanks for your help.

public void startRunning(){
      try{
         server = new ServerSocket(6789, 100); // port no, max users
         while(true){
            try{
               waitForConnection();
               setupStreams();
               connectionRecieving();
            }catch(EOFException eofException){
               showMessage("Server ended connection \n");
            }finally{
               closeConnection();
            }
         }
      }catch(IOException ioException){
         ioException.printStackTrace();
      }
   }

   // Wait for connection
   private void waitForConnection() throws IOException{
      showMessage("Attempting connection... \n");
      connection = server.accept();
      showMessage("Connected to: " + connection.getInetAddress().getHostName() + "\n");
   }

   // Get stream to send and receive data
   private void setupStreams() throws IOException{
      output = new ObjectOutputStream(connection.getOutputStream());
      output.flush();
      input = new ObjectInputStream(connection.getInputStream());
   }

   // Close streams and sockets 
   private void closeConnection(){
      showMessage("----- \nClosing connections... \n");
      try{
         output.close();
         input.close();
         connection.close();
      }catch(IOException ioException){
         ioException.printStackTrace();
      }
   }

Solution

  • To read and write to multiple clients at the same time, you either need separate threads (blocking IO) or if you want to use a single thread, NIO (nonblocking IO).

    You can check out this post about the implementation differences, but NIO is generally the more efficient way to go.

    Using blocking I/O generally follows the code you used above, except you need a separate thread to handle each accepted socket. With NIO, the usage is a little more complicated; check out this tutorial.