views:

131

answers:

1

I'm the network programmer on a school game project. We want to have up to 16 players at once on a LAN. I am using the Server-Client model and am creating a new thread per client that joins. However, a lot of CPU time is wasted just checking on each thread if the non-blocking port has received anything from the client.

I've been reading "Network Programming for Microsoft Windows" by Anthony Johns and Jim Ohlund. They mention two different models for server-client apps.

1.)

  • Using overlapped IO socket options
  • Pass the overlapped struct and a WorkerRoutine to WSARecv
  • Call WSAWaitForMultipleEvents() or SleepEX() to set thread to alertable.
  • Handle Received data in the WorkerRoutines.

2.)

  • Using overlapped IO socket options
  • Create Io Completion Port
  • Create ServerWorkerThreads (however many CUPs you have)
  • Associate Completion port with Socket.
  • Call GetQueuedCompletionStatus in the ServerWorkerThread and handle received data.

I wanted to know which method would best fit my circumstance. The book says the Completion Port model is great for thousands of clients but that makes me think its made for a big server not for a small LAN game. The WorkerRoutines/Event system seems simpler.

+2  A: 

You should stop using non-blocking ports. They're really most useful for concurrency, and you have threads for that.

Just make each thread in the team wait on the port, and when it unblocks, it'll have something to do so you don't waste time spinning. If you have other things to do (like update game state), do that with other threads that don't do any network I/O at all.

And make sure to use synchronization primitives (semaphores) to keep from getting out of sync with yourself.

That's the super multi-threaded way to do it, and you probably should use it. The other way is to have a lock-step advancing state machine that updates all clients round-robin. This is rather useless if you want to play across the internet since varying pings will make your game run at varying speeds.

Southern Hospitality
So when my port is blocking does it waste CPU cycles or does it sleep?
Cory Carlson
The thread that is blocking goes to sleep until data arrives.
James McNellis