我的作业包括使用 UDP 服务发送图像文件(使用我成功实现的 java)。我的教授要求包括:
"The exchanged data messages must also have a header part for the sender to include 16-bit message sequence number for duplicate filtering at the receiver end"
如何做到这一点?
最佳答案
我假设要创建您的 UDP 数据包,您正在使用 ByteArrayOutputStream 来生成数据。如果是这种情况,只需在该 ByteArrayOutputStream 之上包装一个 DataOutputStream,然后在将图像数据写入流之前调用 writeInt(somesequenceNumber)。
在接收端,做相反的事情,将一个 DataInputStream 包裹在一个 ByteArrayInputStream 周围,然后调用 readInt() 来获取序列号。从那里你可以检查你是否已经收到这个数据包。
有点像
书写面
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
dos.writeInt(sequenceNumber++);
dos.writeInt(imageDataLength);
dos.write(imageData);
dos.flush();
byte[] udpPacketBytes = baos.toByteArray();
阅读面
ByteArrayInputStream bais = new ByteArrayInputStream(udpPacketBytes);
DataInputStream dis = new DataInputStream(bais);
int sequenceNumber = dis.readInt();
if (seenSequenceNumbers.add(Integer.valueOf(sequenceNumber)))
{
int imageLength = dis.readInt();
byte[] imageData = new byte[imageLength];
dis.read(imageData);
}
seenSequenceNumbers 是某个集合
关于java - UDP 客户端/服务器 ....包括用于过滤重复项的 16 位消息序列号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5366566/