我試圖設計一個服務器/客戶端體系結構,並且我想讓你們能夠確定表示和解析不同類型數據包的最佳方式。每種數據包類型都需要進行不同的解析。下面表示我會看到的數據包類型。數據包:有效地表示不同數據包類型
[*packet_type*][length][variable length data]
*packet_type* describes the type of packet we're sending (client login, server returning authentication, data, etc)
length describes how much data to read
variable length data contains the info to be sent. it will be specialized based on the packet_type. the data will be variable regardless of
我進去看了tcphdr結構,我想我可以使用相似類型的報頭爲代表* packet_type *和長度。然後,我會使用一個字符串來表示數據。
public class Packet {
public enum PKT_TYPE {
CL_REGISTER,
CL_LOGIN,
SRV_AUTH,
SRV_GAME_INFO,
}
PKT_TYPE _packet_type;
int _length;
String _data;
}
現在有一個共同的基礎,我想我可以實現每個* packet_type *的類和發送/接收方法。但是,我覺得這不是很可擴展性,並且很難維護。安(粗糙,僞)的這個例子是
public class Packet {
...
public class Pkt_CL_LOGIN extends Packet {
String _loginname;
String _password;
public boolean send() {
//socket.write(CL_LOGIN, length, _loginname+_password);
}
public Pkt_CL_LOGIN parse(String data) {
//removed header already, so first byte will be data
//extract login + password
_loginname = login;
_password = password;
return this;
}
}
public Packet receive() {
//read from socket
//parse header for packet_type
switch (packet_type)
case CL_LOGIN:
return (new Pkt_CL_LOGIN()).parse(data);
}
}
誰能給我如何以不同的方式實現這一一些建議?我不太清楚,如果有一個,但也許更有經驗的人可以給我一些見解(比如他們是如何做到這一點在多人遊戲等)
謝謝!
嘿朱利安。我真的很喜歡你使用Protocol Buffers的建議。這正是我所尋找的 - 這看起來很容易擴展和維護。我希望我能投票給你,但不幸的是我還沒有足夠的代表。 – John 2012-02-12 20:30:06
它確定大聲笑,只是接受問題。 – 2012-02-12 22:45:40