我正在实现一个 p2p 应用程序,其中节点通过 UDP 数据包进行通信。从 InputStream 读取的数据包有时不完整。
这是我的代码:
...
protected String key;
protected Identifier messId; //Identifier hold a BigInteger
protected String range;
protected String concat;
……
public ReplicationMessage(DataInput in) throws IOException {
fromStream(in);
}
public void fromStream(DataInput in)
try {
super.fromStream(in);
int length=in.readInt();
byte[] data=new byte[length];
in.readFully(data);
concat = new String(data);
System.out.println("concat: "+concat);
messId = new Identifier(in);
} catch (IOException e) {
e.printStackTrace();
}
}
public void toStream(DataOutput out) {
try {
super.toStream(out);
byte[] data = concat.getBytes();
out.writeInt(data.length);
out.write(data);
messId.toStream(out);
} catch (IOException e) {
e.printStackTrace();
}
}
读取数据包有时是完整的,例如
连接:179136678282544:140737488355328
但有时不完整,例如
连接:179136678282544 连接:179136678282544 连接:179136678282544
谁能告诉我问题是什么?
非常感谢
以下是发送/接收 UDP 数据包发送的代码:
private void sendMessage(int comm, Message message, InetAddress ip, int port) 抛出 IOException {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
DataOutputStream dout = new DataOutputStream(bout);
dout.writeInt(comm);
dout.writeByte(message.code());
message.toStream(dout);
dout.close();
byte[] data = bout.toByteArray();
if (data.length > DATAGRAM_BUFFER_SIZE) {
throw new IOException("Message too big, size="+data.length+
" bytes, max="+DATAGRAM_BUFFER_SIZE+" bytes");
}
DatagramPacket packet = new DatagramPacket(data, data.length, ip, port);
socket.send(packet);
}
用于接收 UDP 数据包
byte[] buffer = new byte[DATAGRAM_BUFFER_SIZE];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
发送节点和接收节点属于一台机器。Buffer接收包设置为10*1024字节,远大于包长度
这是将传入数据包转换为流的代码
ByteArrayInputStream bin = new ByteArrayInputStream(packet.getData(),
packet.getOffset(), packet.getLength());
DataInputStream din = new DataInputStream(bin);
int comm = din.readInt();
byte messCode = din.readByte();
Message message = factory.createMessage(messCode, din);