class UdpSendDemo {
public static void main(String[] args) throws IOException {
DatagramSocket ds = new DatagramSocket();
byte[] data = "我是发送端".getBytes();
DatagramPacket dp = new DatagramPacket(data,data.length, InetAddress.getByName("127.0.0.1"),10000);
ds.send(dp);
ds.close();
}
}
/**
* 接收udp传过来的数据
* 定义udpsocket服务 监听一个端口
* 通过socket服务的recive方法将收到的数据存入以定义好的数据包中
* 打出控制台
* 关闭资源
*/
class UdpReciveDemo {
public static void main(String[] args) throws IOException {
DatagramSocket ds = new DatagramSocket(10000 );
byte[] arrPacket = new byte[1024];
DatagramPacket dp = new DatagramPacket(arrPacket,arrPacket.length);
ds.receive(dp);
String ip = dp.getAddress().getHostAddress();
String data = new String(dp.getData(),0,dp.getLength());
int port = dp.getPort();
System.out.println(ip+":"+data+":"+port);
ds.close();
}
}