我在 JAVA 中通过 TCP 接收字节数据包时遇到一些问题。 我的 TCPServer 类发送 207 字节的数据包。当我发送一个数据包时,程序在控制台中显示“Read 207 byte packet”。并停止。对于下一个数据包,它继续执行,显示“多次测量”和 “读取 1868767867 字节数据包。”。之后接收将永远停止。我不知道为什么它收到 1868767867 字节。我在 wireshark 中检查它,服务器总是发送 207 个字节。
这是我的 TCPClient 类:
public class TCPClient extends Thread {
private ServerSocket serverSocket;
private Socket connectionSocket;
private InputStream inputStream;
private DataInputStream dataInputStream;
public TCPClient() throws IOException {
try {
serverSocket = new ServerSocket(Config.TCP_PORT);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
try {
connectionSocket = serverSocket.accept();
inputStream = connectionSocket.getInputStream();
dataInputStream = new DataInputStream(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
while(true) {
try {
JsonObject json = getJsonFromTcp();
if (json != null) {
String command = json.getAsJsonPrimitive("command").getAsString();
if(command.equals("multipleMeasurement")) {
executeMultipleMeasurement();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private JsonObject getJsonFromTcp() throws IOException {
byte[] buff = new byte[4];
for(int i = 0; i < 4; i++) {
buff[i] = dataInputStream.readByte();
}
int len = (((buff[3] & 0xff) << 24) | ((buff[2] & 0xff) << 16) | ((buff[1] & 0xff) << 8) | (buff[0] & 0xff));
if(len > 0) {
System.out.println("Read " + len + " byte packet.");
byte[] data = new byte[len];
dataInputStream.readFully(data);
String jsonString = new String(data, "UTF-8");
JsonParser jsonParser = new JsonParser();
JsonObject json = jsonParser.parse(jsonString).getAsJsonObject();
return json;
}
return null;
}
private void executeMultipleMeasurement() {
System.out.println("Multiple Measurement");
}
}
有人知道解决办法吗?
最佳答案
看数字1868767867,它的字节是
"%c%c%c%c" % (0x7b,0x22,0x63,0x6f)
'{"co'
因此您可以读取下一条消息的前四个字节作为消息的长度。对于服务器每次恰好发送 207 个字节的说法,最可能的解释是服务器在总消息长度中包含了长度前缀的长度(4 个字节)。根据预期的协议(protocol),读取(长度 - 4)字节作为数据包的主体可能是合适的。
// Account for the length of the header
len -= 4;
if(len > 0) {
System.out.println("Read " + len + " byte packet.");
byte[] data = new byte[len];
dataInputStream.readFully(data);
第二种可能性是服务器正在测量字符串中的字符数,然后使用该长度作为它将发送的 utf-8 转换字节缓冲区的长度,包括一些导致结果的非 ascii 字符缓冲区更长。
如果没有看到服务器代码,就不可能确定这里发生了什么。
关于java - TCP接收字节包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39299817/