【发布时间】:2016-09-02 19:53:00
【问题描述】:
我在 JAVA 中通过 TCP 接收字节数据包时遇到了一些问题。 我的 TCPServer 类发送 207 字节数据包。当我发送一个数据包时,程序在控制台中显示“读取 207 字节数据包”。并停止。随着下一个数据包继续执行,显示“多重测量”和 “读取 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");
}
}
有人知道解决办法吗?
【问题讨论】: