简体   繁体   English

可以将接收到的DatagramPacket用于再次发送吗?

[英]Can a received DatagramPacket be used to be sent again?

I am testing a UDP echo server, is the following code correct? 我正在测试UDP回显服务器,以下代码正确吗?

DatagramSocket s = ...
DatagramPacket p = new DatagramPacket(new byte[512], 512);

...

s.recieve(p);
s.send(p);

My question is, can I send the DatagramPacket just as I recieved it? 我的问题是,是否可以像我收到的一样发送DatagramPacket According to the java specification, the contructor I used constructs a DatagramPacket 'for recieving use'. 根据java规范,我使用的构造函数构造了一个“用于接收用途”的DatagramPacket。 I am not sure if that state changes when the packet has been modified through s.recieve , or if that 'for recieve use state' is permanent. 我不确定通过s.recieve修改数据包时该状态是否会更改,或者“用于接收状态”是否是永久性的。

If the code is correct, is there any reason why in the tutorial they construct a whole new DatagramPacket ? 如果代码正确,那么为什么在本教程中他们构造了一个全新的DatagramPacket (maybe just clarity?) https://docs.oracle.com/javase/tutorial/networking/datagrams/clientServer.html (也许只是为了清楚?) https://docs.oracle.com/javase/tutorial/networking/datagrams/clientServer.html

Yes, and it's quite common. 是的,这很普遍。 If you receive a request, the DatagramPacket already has the return address in it, so all you need to do is put the response data into it and send it back. 如果收到请求,则DatagramPacket中已经有返回地址,因此您所需要做的就是将响应数据放入请求中并发送回去。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM