【发布时间】:2014-11-23 09:49:06
【问题描述】:
我正在尝试构建一个基本的代理 4 服务器,我必须解析一个数据包并提取它的信息,如下所示:
1 byte (version)
1 byte (command)
2 byte (port)
4 byte (ip)
X byte (userID, builds a string by looping until '\0' is found)
到目前为止,这是我的代码:
InputStream reader = socket.getInputStream();
byte[] ver = new byte[1];
byte[] cmd = new byte[1];
byte[] port = new byte[2];
byte[] ip = new byte[4];
reader.read(ver, 0, 1); //should be: 4
reader.read(cmd, 1, 1); //should be: 1
reader.read(port, 2, 2); //should be: 00, 80
reader.read(ip, 4, 4); //should be: 217, 70, 182, 162
这是我从代码中得到的回复:[4, 1, 0, 80, -39, 70, -74, -94]
由于某种原因,我得到的 IP 部分总是错误的,我真的不知道为什么。我的第二个问题是:如果找不到 \0 字节,是否有一种简单而干净的方法来获取最后一个 userID 字符串部分,而不必构建一个可能最终永远挂起的混乱循环?
【问题讨论】:
-
你能转储
Stream数据byte-by-byte看看它包含什么吗? -
@BoristheSpider: [4, 1, 0, 80, -39, 70, -74, -94, 0, 0](无用户 ID)
标签: java sockets networking network-programming