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.