package UDP;
import org.junit.Test;
import java.io.IOException;
import java.net.*;
public class UDPTest {
@Test
public void send() throws IOException {
// 1.
DatagramSocket socket = new DatagramSocket();
// 将信息都放在DatagramPacket中
String str = "我是UDP发送的信息";
byte[] data = str.getBytes();
InetAddress ip = InetAddress.getLocalHost();
DatagramPacket packet = new DatagramPacket(data, 0, data.length, ip, 8090);
// 2.
socket.send(packet);
socket.close();
}
@Test
public void receiver() throws IOException {
// 1.接收端指定端口号
DatagramSocket socket = new DatagramSocket(8090);
byte[] buffer = new byte[100];
DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);
// 将接受的信息保存到buffer[]中
socket.receive(packet);
System.out.println(new String(packet.getData(),0,packet.getLength()));
socket.close();
}
}
?
|