开发者

How to avoid create one thread per room (group of players)

I have made a game (is still in Beta, need improvements, and other things), and I would like to know if exists a better approach of what I have done in my game servers. (Programmed on C#)

The process to play a game is something like this: Client application (player) → connect to lobby server → check for an available room with the game he likes to play → the lobby answer the request and point the player to right game server (all using "raw" TCP/sockets).

Each game server automatically start the game when exists at least 4 players in the room (multiple rooms are possible) and a maximum of 12. Each room is launched in a different thread, I mean, I create one thread per room (4-12 players), so if I have 1.200 (many more can be expected by game server) then will be at least 100 threads (even more depending of how many players are really in each room). The main thread (and is work) plus all the threads created will be consuming all resources in my server... so, I was wondering if anybody can suggest a better idea or approach?

Keep in mine that all the connections are asynchronous, except in the room, I开发者_如何学编程 mean, in the room the server must wait for the move of one player (like a Ludo game or a bet) to let the next player (in the room) do the same. In fact, the buttons to make a move are enabled only to the player that is turn to move on. For that reason the transmission in place is synchronous and when somebody move the rest receive their respective notifications.


If you can wait on multiple sockets in the same thread (that I don't know and it's probably OS-specific) and you can unambiguously associate incoming data with a particular socket (this you should be able to, I think), then you can service all rooms (or just a few) sequentially in the same thread and thus save on per-thread data structures in the OS and the per-thread stack. You will likely need to implement some kind of a state machine to achieve that and rearchitect your data structures.


Coming from a MUD development background, the usual process for this kind of thing is to work on a "heartbeat" model:

  1. You have a timer thread, which fires a heartbeat event/message at regular intervals.
  2. With each heartbeat, a subscribed reader-thread checks all the connected sockets to see if they have any data to read. If so, the commands (button presses, etc) can be put in a queue (along with an indicator of which user, room, etc) to be read by the main game processor.
  3. Game processor simply processes messages from the incoming queue, and produces responses (which can be put on an outgoing queue for delivery, if you fancy it).

This is how I've always done it when writing chat servers, talkers, and MUDs, and sounds like it could be a good fit for your requirements too.

HTH

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜