我有一个带有远程客户端的套接字服务器,它可以正常工作。打开客户端并登录后,我注意到有时会出现错误,这似乎是由于客户端在不应该读取 int 时导致的。
登录后,服务器会向客户端发送一系列消息/数据包,这些消息/数据包可以是字符串消息,也可以是用于在客户端加载变量的信息。
有时,在登录时,会抛出一个错误,表明客户端已读取大小为 0 或非常大的数据包。在将大数字转换为ascii时,我曾经发现它有点像字符串“sk”。(我在我的代码中找到了这个字符串,所以它不是完全随机的)。
查看我的代码,我不确定为什么会这样。客户端是否有可能在错误的时间读取 int?如果是这样,我该如何解决这个问题?
InetAddress address = InetAddress.getByName(host);
connection = new Socket(address, port);
in = new DataInputStream(connection.getInputStream());
out = new DataOutputStream(connection.getOutputStream());
String process;
System.out.println("Connecting to server on "+ host + " port " + port +" at " + timestamp);
process = "Connection: "+host + ","+port+","+timestamp + ". Version: "+version;
write(0, process);
out.flush();
while (true) {
int len = in.readInt();
if (len < 2 || len > 2000) {
throw new Exception("Invalid Packet, length: "+len+".");
}
byte[] data = new byte[len];
in.readFully(data);
for (Byte b : data) {
System.out.printf("0x%02X ",b);
}
try {
reader.handlePackets(data);
} catch (Exception e) {
e.printStackTrace();
//connection.close();
//System.exit(0);
//System.out.println("Exiting");
}
}
//Here is code for my write function (Server sided):
public static void write(Client c, Packet pkt) {
for (Client client : clients) {
if (c.equals(client)) {
try {
out.writeInt(pkt.size());
out.write(pkt.getBytes());
out.flush();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
所以看看 write 函数,我真的不明白它是如何让客户端感到困惑的,并让它为一个数据包读取两次数据包的大小(至少这是我认为正在发生的事情)。
如果您需要更多信息,请询问我。