编写代码
1,接收端 UdpServerDemo01
package com.xiang.lesson03;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class UdpServerDemo01 {
public static void main(String[] args) throws Exception {
// 开放端口 ;
DatagramSocket socket = new DatagramSocket(9999);
// 接收数据 包
byte[] buffer = new byte[1024];
// 接收
DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
// 阻塞/接收
socket.receive(packet);
// 输出
System.out.println(packet.getSocketAddress());
System.out.println(packet.getAddress().getCanonicalHostName());
System.out.println(new String(packet.getData(),0,packet.getLength()));
// 关闭连接
socket.close();
/*
先启动服务器,
要启动客户端
*/
}
}
2,发送端 UdpClientDemo01
package com.xiang.lesson03;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;
//upd 不需要连接 服务器;
public class UdpClientDemo01 {
public static void main(String[] args) throws Exception {
// 1, 建立一个 包 ,或者socket ; 数据包
DatagramSocket socket = new DatagramSocket();
// 2,建个包;
String msg="你好啊,服务器";
// 发送的人
InetAddress localhost = InetAddress.getByName("localhost");
int prot =9999;
// 数据 ,数据的长度 起始,要发送的人 ,端口号;
DatagramPacket packet = new DatagramPacket(msg.getBytes(StandardCharsets.UTF_8),0,msg.getBytes(StandardCharsets.UTF_8).length,localhost,prot);
// 3,发送包;
socket.send(packet);
// 4,关闭流
socket.close();
}
}
3,运行结果