过去几天我一直在使用TCP/IP通信(使用Java和C#)搞了很多。我了解它是如何工作的并且能够使用它。我的问题更多的是一个代码设计问题,它是如何完成一个真正的沟通的最佳和简单的方法。网络通信TCP [代码设计]
例如我构建了我自己的多用户聊天服务器。我希望我的通信能够决定采用Auth请求还是新聊天消息能够获取当前用户列表等。
我自己实现了几种方式,但我不太满意因为我认为这是一种更加标准和美观的方式。
我首先想到的是用分隔符至极一个字符串被分裂,这是我在Java中我的通信实现的例子:
//The Object-types im Using
clientSocket = new Socket(host, port_number);
_toServer = new PrintStream(clientSocket.getOutputStream());
_fromServer = new DataInputStream(clientSocket.getInputStream());
//Example Commands my Client sends to the server
_toServer.println("STATUS|"); //Gets the Status if server is online or closed (closed can occur when server runs but chat is disabled)
_toServer.println("AUTH|user|pw"); //Sends an auth Request to Server with username and Password
_toServer.println("MESSAGE|Hello World|ALL"); //Sends hello World in the Normal Chat to all Users
_toServer.println("MESSAGE|Hello World|PRIVATE|foo"); //Sends hello World only to the user "foo"
_toServer.println("USERS|GET"); //Request a list of all Connected Users
//Example In the Recieved Message Method where all The Server Messages Get Analyzed
serverMessage = _fromServer.readLine(); //Reads the Server Messages
String action = serverMessage.split("|")[0];
if (action.equals("USERS")) { //Example "USERS|2|foo;bar"
String users[] = serverMessage.split("|")[2].split(";");
}
if (action.equals("MESSAGE")) { //Example "MESSAGE|Hello World|PRIVATE|foo"
if(serverMessage.split("|")[2].equals("ALL") {
//Code and else for private....
}
}
if (serverMessage.equals("STATUS|ONLINE")) {
// Code
// I leave out //Code and } for the next If statements
}
if (serverMessage.equals("STATUS|OFFLINE")) {
if (serverMessage.equals("AUTH|ACCEPTED")) {
if (serverMessage.equals("AUTH|REJECT")) {
这是方法的正常进行?广告你看我需要发送与代码对应的状态码和对象。香港专业教育学院思想以字节为藏汉写入数据,并实现了“为每个对象解码器”,例如:
int action = _fromServer.readInt();
//opcodes is just an Enum Holding the corresponding int
switch(action) {
case(opcodes.MESSAGE):
break;
case(opcodes.AUTH):
break;
}
注意,这是更比一般的设计问题不只是这个聊天服务器实例,我认为,即时通讯实现一个基于网络的控制台游戏只是为了练习。
有没有更好的方法来做到这一点,甚至是一个API /框架?
在此先感谢!
感谢您的快速答案,我已经搞砸了几个游戏,这有一个Documented Protocoll和那些总是像我的第二个例子,第一个4/8字节是行动代码,其余的数据如下。我希望有一些东西像接口一样在对象上实现,以便能够将em转换成这样的协议形式 – Angelo 2012-02-27 10:59:35