node.js multiplayer game server architecture
Say you're making a Texas Hold'em server. We have a single lobby and multiple rooms in which game sessions occur. At what level do you separate rooms?
Initially I thought I'd spawn an instance of node for each room in the lobby. The major benefit being, if a game crashes, it would definitely do so in isolation.
I lost confidence in t开发者_Python百科his approach when I realized that chat-servers typically run as a single daemon managing multiple rooms. It does seem ugly to need a separate listening port for every room in the lobby. I think it also becomes easier to manage identity across rooms - e.g., if the player changes their name.
Any thoughts? Does it make sense to "multiplex" a single node server to manage multiple game room sessions?
Technically, you don't need to listen on separating ports for each room. This is possible because OS supports parent & child processes share the same socket (file) descriptor. You can employ the WebWorker node module to achieve this. With this architecture, you have automatically got a load balancing module that can distribute incoming connections to different child processes using the OS process scheduler.
However, with your system, the hardest part is about how to share common data among these processes because they have their own memory spaces. Luckily, there are some ways to share this data (online sessions, rooms, score table...) but they can be quite complicated. One way is to let the child processes to communicate with the master via IPC (socket), and another way is to use a shared memory area (database, memcached...) that everyone can access on the fly.
I would recommend that you build your system using single node process architecture first (if you're going to use websocket, you can handle quite big number of concurrent connections already), then when you need to expand your system, use webworker architecture. Moreover, it won't take much time to migrate if you already use a common place for storing/retrieving data (database, memcached, redis keystore...).
I would recomment Hook.io for your application. It's framework for letting multiple node processess talk through events.
精彩评论