服务器和客户端之间的协议:
二进制协议,每条第一个字节为协议名字字节,表明协议的类型。每种类型的协议有固定的长度。
例如:
命令字节 长度 内容 含义
01 17 以0x00结尾的字符串,代表别名 登陆
02 17 以0x00结尾的字符串,代表别名 退出
21 98 char* alias, char* content,以0x00结尾的字符串,代表输入的文字 文字输入 很多socket例子都是直接传递字符串并显示。这里该如何传递数据并解析。
二进制协议,每条第一个字节为协议名字字节,表明协议的类型。每种类型的协议有固定的长度。
例如:
命令字节 长度 内容 含义
01 17 以0x00结尾的字符串,代表别名 登陆
02 17 以0x00结尾的字符串,代表别名 退出
21 98 char* alias, char* content,以0x00结尾的字符串,代表输入的文字 文字输入 很多socket例子都是直接传递字符串并显示。这里该如何传递数据并解析。
http://blog.csdn.net/YidingHe/archive/2009/04/20/4093892.aspx
ServerSocket ss = new ServerSocket(20002);
Socket socket = ss.accept();
InputStream in = socket.getInputStream();
dis = new DataInputStream(in);
byte status = dis.readByte();
System.out.println("状态:" + status);
if (status == 0x01) {
handle(17);
} } public void handle(int length) throws IOException {
byte[] msg = new byte[length - 1];
dis.read(msg);
System.out.println(new String(msg));
} public static void main(String[] args) throws IOException {
System.out.println("Server start...");
Server s = new Server();
s.start();
}
}public class Client {
private Socket socket = null;
public void connect() throws UnknownHostException, IOException{
socket = new Socket("localhost",20002);
OutputStream out = socket.getOutputStream();
DataOutputStream dos = new DataOutputStream(out);
byte[] str = "这是一个测试用的".getBytes();
int length = str.length;
byte[] msg = new byte[length + 1];
msg[0] = 0x01; System.arraycopy(str, 0, msg, 1, length);
for (int i = 0; i < msg.length; i++) {
System.out.print(msg[i] + " ");
}
dos.write(msg);
}
public static void main(String[] args) throws UnknownHostException, IOException {
Client c = new Client();
c.connect();
}
}