开发者

Generic way to handle many types of messages

I'm working on a little client that interfaces with a game server. The server sends messages to the connected client over HTTP. Its relatively easy to parse the text messages coming into the client and form responses to send back.

Now what I'm trying to figure out is how to break up the process. I want to have a thread receiving the messages, parsing them into some data object, and placing them into an "incoming" queue to be processed. Then another thread reads messages from this queue and processes them (the brains or AI of the client) and makes responses back to the server.

I want to have the thread that watches the incoming data to do process the text (break up the messages, pull the important data out, etc.) so the AI thread doesn't have that overhead. But the problem is that the server can send a couple hundred different types of messages to the client (what the client can see, other players, if you are firing etc). I want to package this data into a neat little structure so the AI can handle it quickly, and the AI can be rewritten easily.

But how do I write a function that can pull something off a queue and know what type of message it is (so I know what data is contained within the message)?

Example messages:

ALIVE (tells you if you are alive)

It has only one data object, the current game time

DAM (tells if you are damaged)

Has a whole bunch of data, who damaged you, how much, what gun it is, if you can see them, etc.

It is possible to make an object that can handle all of these different message types and be interpreted by a single function? Very few messages have common attributes, so I don't think i开发者_运维知识库nheriting or just making one really big message class would be very good...

I'm not looking for a full solution here, just point me in the right direction and hopefully I'll be able to learn a bit on the way :-)


Basically what you're asking about is called a protocol: how data is exchanged and interpreted. Traditionally you'd define your own (and odds are they'd tend to start out rather naive -- sending plain text data with newlines to indicate the end of a command, or something like that). After a while you begin to realize that more is needed (how do you handle binary data? how do you handle errors? etc, etc)

Fortunately there are libraries out there to make life easier for you. These days I tend to favor simple RPC-like libraries for most of my needs. Examples include protocol buffers (by Google), Apache Thrift (by Facebook) and Apache Avro.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜