Wlofrevo Kcast
Wlofrevo Kcast

Reputation: 629

Must a listening socket runs in thread?

I have some problems understanding how a socket should be handled. I get that server socket must runs in its own thread, because it must check if there are new connections. Now, i'm not sure if every socket opened by a new connection should runs in a thread.

What i have in mind is checking every x time the socket states. If it has something to be read, then read. If not, check the next socket. I see some examples where this process is done in a thread, but i dont want a socket to do stuff, just want to read if it has some data, and process them.

Upvotes: 1

Views: 436

Answers (3)

user207421
user207421

Reputation: 311028

The problems with round-robin using available() are many.

  1. It assumes that available() actually works, which isn't guaranteed.
  2. It assumes that all clients need the same amount of service.
  3. N-1 clients wait while one client is serviced.
  4. A non-responsive client can block not only your application but all the other clients.

I'm sure there are more.

Don't do this. Use threads or NIO.

Upvotes: 1

Philipp
Philipp

Reputation: 69703

You can also have one thread which communicates with all sockets in a round-robin manner. It checks each socket if it has new data, and when it hasn't it checks the next.

Another alternative is to use NIO (New Input/Output).

The idea behind NIO is that you have a thread with one Selector which owns multiple Channels (a channel can be a network socket or any other IO interface). You then call selector.select() in a loop. This method blocks until one or more channels have data, and then returns a set of these channels. You can then process the data the channels delivered.

Here is a tutorial.

Upvotes: 2

greedybuddha
greedybuddha

Reputation: 7507

The answer is no, you don't need to listen in a separate thread. But, just realize that while you are "listening" your entire program will be waiting for that to complete before moving onward.

So unless you are fine with your entire program waiting, I would suggest a separate thread.

Upvotes: 2

Related Questions