UDP网络编程
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-aeBiAPbN-1601884029350)(C:\Users\PePe\AppData\Roaming\Typora\typora-user-images\image-20201005150858686.png)]](https://i-blog.csdnimg.cn/blog_migrate/5b768ada498f87728522826d463c82c6.png#pic_center)
public class UDPTest {
@Test
public void sender() throws IOException {
DatagramSocket socket = null;
try {
socket = new DatagramSocket();
String str = "我是UDP方式发送的导弹";
byte[] data = str.getBytes();
InetAddress inet = InetAddress.getByName("127.0.0.1");
DatagramPacket packet = new DatagramPacket(data,0,data.length,inet,9090);
socket.send(packet);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null){
try {
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
@Test
public void receiver() throws IOException {
DatagramSocket socket = null;
try {
socket = new DatagramSocket(9090);
byte[] buffer =new byte[100];
DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);
socket.receive(packet);
System.out.println(new String(packet.getData(),0,packet.getLength()));
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null){
try {
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}