Client/server sharing packet logic

I haven’t seen many examples where the client and server use the same classes for their packet logic. Is there any reason for this? It could be used in a JS project, so the same file would be used by both the Node server and the user’s browser. This approach would mean that both sides would have the packet’s signature built in.

Here is some psuedocode demonstrating it:

[code=JavaScript]enum PacketDirection {
SERVER_TO_CLIENT,
CLIENT_TO_SERVER
}

interface Packet {
name: string;
direction: PacketDirection;
payload: any;
}

class AddPlayerPacket implements Packet {
name = “add_player”;
direction = PacketDirection.SERVER_TO_CLIENT;
payload = undefined;

constructor(id : number, name: string) {
	this.payload = {
		id: id,
		name: name	
	};
}

}

class SendChatPacket implements Packet {
name = “send_chat”;
direction = PacketDirection.CLIENT_TO_SERVER;
payload = undefined;

constructor(message: string) {
	this.payload = {
		message: message	
	};
}

}

var add_player_pkt = new AddPlayerPacket(9, “Boris”);
var send_chat_pkt_1 = new SendChatPacket(“Hello! This is my first message!”);
var send_chat_pkt_2 = new SendChatPacket(“And this is another!”);[/code]

This would be useful on applications where both the back-end and the front-end are written in JavaScript and need to share models.

if you want to share packet structure between server and client, you definitely want to use Google Protobuffers (or one of the many open source spinoffs like Msgpack, capnproto, Facebook Thrift)

“Is there any reason for this?”

  • Yes, generally speaking its because the client -> server packets are a lot different than the server -> client packets.