tags:

views:

322

answers:

3

I have a game I am working on in C++ and OpenGL. I have made a threaded server that right now accepts clients (the game) and receives messages from them. Right now the game only sends messages. I want both the game and server to be able to send and receive, but I'm not sure the best way to go about it. I was considering using a thread for sending and one for receiving, both on the same socket. Right now the game runs in a single thread, and the server makes a separate thread for each client.

Looking for suggestions on how to go about it for the game as well as the server (unless your suggestion is the same for both). Any questions, feel free to ask :)

Thanks!

A: 

Consider using Boost.ASIO that implements this well with a C++ API (allowing many different approaches besides just asynchronous I/O). There are plenty of tutorials. However, for the absolute highest performance, you should probably not use threads.

Tronic
For the very highest performance you need one thread per execution unit, *and* a asynchronous I/O engine.
Zan Lynx
True, bad use of language from my part.
Tronic
Thank you for the replies so far. The game is a first person shooter (you can see progress at my site) so speed is critical, but I am not worried about having more than say 50 people connected at most. I am doing everything from scratch on my own, so while I appreciate the idea to use the Boost library, I would prefer to not use anything someone else created unless necessary (aka Win32, WinSOck APi's, etc..). I will look into async methods :)
Se7eN
Non-blocking IO is what you really want - select() or poll(), depending on what's available.
kyoryu
+1  A: 

What you need to do is set up an outgoing queue of messages for each client. Say you have 2 clients connected to the server, one being serviced by thread A and the other by thread B. Thread A should do a WaitOnMultipleObjects() on its socket and on a semaphore/mutex/condition variable for its queue. That way, if it gets something in its queue, it can wake up and send it out. If it gets a message from the client that it needs no give to client B, it will process that message and put it in thread B's outgoing queue.

This is a very simple synchronization scheme. If your game is very complex or massive, you will have to do something much more clever than this.

Variable Length Coder
+1  A: 

Don't use threads in a game server. Many professional, AAA game servers are single-threaded - every one I've ever seen, in fact.

kyoryu