【发布时间】:2014-12-20 21:33:43
【问题描述】:
我有一个带有远程客户端的套接字服务器,它可以正常工作。打开客户端并登录后,我注意到有时会出现错误,这似乎是由于客户端在不应该读取 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 函数,我真的不明白它是如何混淆客户端并让它读取一个数据包两次的数据包大小(至少我认为这是正在发生的事情)。
如果您需要更多信息,请询问我。
【问题讨论】:
-
请向我们展示您的 Packet 类。
-
我已在此处提供。 pastebin.com/dx7bYNPS
标签: java sockets client packet server