我正在执行一个 p2p 应用程序, 其中节点通过 UDP 软件包进行通信。 从 InvestiveStream 读取的软件包有时不完整 。
这是我的代码:
.
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();
}
}
例如,读取包的某个时间是完整的
体积: 179,16678282544: 14073748835328
例如,有些时不完全, 但有时不完全, 例如
concat: 179136678282544 concat: 179136678282544 concat: 179136678282544
谁能告诉我有什么问题吗?
非常感谢
Here are the code for sending/receiving the UDP packet for sending:
private void sendMessage(int comm, Message message, InetAddress ip, int port) throws 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);
发送节点和接收的节点属于一台机器。 缓冲接收包设为 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);