3
\$\begingroup\$

I'm writing a simple networked game in C/C++. To keep things simple I'm using TCP.

In my server's game loop I'm using a POSIX select() with a zero second timeout for two things:

  • Discover incoming data from connected clients
  • Discover new incoming connections

Is this a reasonable way to do it? Instead of using select() I could just loop through all connected socket descriptors and call recv() (or something like it) for each, to see if there is any new data. Would that be better?

The same question goes for the client. Note that on the client there's only one socket descriptor. Should I here use select() and a zero second timeout to find out if there's any new data incoming, or should I just call recv() on each game tick?

Or perhaps it would be even better if I pushed networking to a separate thread?

\$\endgroup\$

3 Answers 3

2
\$\begingroup\$

For most real-time, interactive games, there's no benefit to moving your networking code into a separate thread; it just makes the code more complicated, creates more edge cases to have to cope with, and makes the game's networking more difficult to write and debug, without giving you any benefits.

Checking for activity using a non-blocking call to select() once each time through your game's main loop should be fine, unless you have some reason why your specific game's networking system needs to be multi-threaded.

\$\endgroup\$
0
\$\begingroup\$

If you can afford, from a complexity standpoint, to make networking threaded that would likely be your best option. That being said POSIX select will function fine otherwise.

\$\endgroup\$
0
\$\begingroup\$

If you're going to publish the network calls on a separate thread - feel free to do that but when you delegate events off to other systems in your game via packets you should make sure you try and call those from the main loop function. Otherwise, you're going to be in for a nasty concurrency issue. :) Start with one thread, let it go. Profile your game. If you find networking is sucking too much CPU, only then should you consider more complex implementations. Don't overdo it - you'll never finish your game if you stack on layers of complexity needlessly.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .