juanjalvarez
juanjalvarez

Reputation: 15

Java single-threaded multi-user chat program

So I'm working on this recreational project to learn more about java networking and so far every tutorial or documentation I've come across involves creating a new thread for each client connection to wait for input. I'm wondering if it's possible to handle the list of client connections with a single thread? I tried doing something like the following code but it didn't work.

while(true){
     for(Client c : list){
          DataInputStream dis = new DataInputStream(c.getSocket().getInputStream());
          if(dis.readLine()!=null){
               //Code
          }
          dis.close();
     }
}

Upvotes: 0

Views: 846

Answers (1)

spudone
spudone

Reputation: 1277

Yes it is possible with a single thread using the NIO package. This will allow you to set up non-blocking IO and multiplex across channels within your single thread. It's not exactly trivial but there's a decent example here.

Your example above will block on the readLine() call until data is available on the Socket. If one of your clients is waiting on data, the while loop will never proceed and you'll never service the other clients.

Upvotes: 2

Related Questions