I am programming a 2D game in a server/client architecture with C# and lidgren. When a client sends a message to the server, how does the server know what to do with that message data?

The client could send different kinds of things, for example the coordinates of player 1 and 2 or the health. So how does the server know its the coordinates and stuff?


In the data you send with the message, you include information about what the purpose of the message is. Not just the relevant data. For example, you'd create an enumerate of possible message types:

enum MessageType {

When you send some data related to moving a player, you don't just send the new position, you prefix the message with the message type MovePlayer. Likewise with sending a message about players attacking, or players disconnecting, or whatnot.

The message type tells the receiver (client or server) how to interpret the rest of the data in the message, which is why it's got to be one of the earliest pieces of data read from the message. Once you read the message type, you know if the subsequent data is a set of floats for position, an amount of health to deduct from a specific player, and so on.

Both the client and the server must (usually) have a mapping of message type to message format, and they must be agreement on this mapping. It's common, therefore, to put these messages and the definitions of the subsequent data into common code that can be shared between the client and the server.

(You can create message formats that are self-describing, so that the receiver of the message need not agree exactly with the sender on the format, however that's a whole different subject and often too verbose for most game networking protocols.)

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.