UDP网络编程:
@Test
public void test1(){
try(DatagramSocket socket = new DatagramSocket();) {
String str = "我是UDP方式发送的数据报";
byte[] data = str.getBytes();
InetAddress inet = InetAddress.getLocalHost(); // 获取发送端的IP
DatagramPacket datagramPacket = new DatagramPacket(data,0,data.length,inet,8899);
socket.send(datagramPacket);
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void test2(){
try(DatagramSocket socket = new DatagramSocket(8899);) {
byte[] data = new byte[1024];
DatagramPacket packet = new DatagramPacket(data,0,data.length);
socket.receive(packet);
System.out.println(new String(packet.getData(),0,packet.getLength()));
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}