package com.atguigu.java2;
import org.junit.Test;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
/**
* @author Dxkstart
* @create 2021-06-05 18:04
*/
public class UDPTest {
@Test
public void send(){//发送端
DatagramSocket socket = null;
try {
socket = new DatagramSocket();
String str = "我是UDP发送的导弹";
byte[] data = str.getBytes();
InetAddress inet = InetAddress.getLocalHost();//本地地址
DatagramPacket packet = new DatagramPacket(data,0,data.length,inet,9090);
//发送
socket.send(packet);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(socket != null) {
socket.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Test
public void receiver() throws IOException {//接收端
DatagramSocket 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()));
socket.close();
}
}