Handling data from a collection of (persistent) inputstreams in "real time"
Alan Su
Greenhorn
Joined: Jul 11, 2004
Posts: 2
posted
0
Hi, I am just writing a little project for fun. Basically its like a game that allows many ppl/players to connect. So I have a collection of socket connections and their input/output streams. I am not sure how I should design the part for reading from these input streams. For now all I can think of is either make a thread for each connection, wait till all the information i need is received through blocking read, then send it to the "engine". This could be bad if I ever have lots of players because lots of threads are created. Or, I can have non blocking read, and have the server poll every connection every .2 seconds. But polling is again ugly. So which way is better? or is there any alternatives? maybe like without using so many threads and allow the OS to send an event to notify the engine whenever new data arrive, so I don't need to poll.
Thank you very much.
Ernest Friedman-Hill
author and iconoclast
Marshal
The traditional way to do this was to use a thread per input stream. But starting in JDK 1.4, there's the java.nio package, which includes a "select"-like functionality that lets you wait for input to appear on any of a collection of input channels. Here is a resonable place to start learning about NIO.
Cool, thanks so much, that seems to work in my case .
Well, if there are 100 players, there will be hundred thread (just planning ahead if somehow I get that many ); I just thought that would be over use of thread.