package cn.itcast_03;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

/*
* 多次启动接收端:
* Unrecognized Windows Sockets error: 0: Cannot bind
* 端口被占用。
*/
public class ReceiveDemo {
public static void main(String[] args) throws IOException {
// 创建接收端Socket对象
DatagramSocket ds = new DatagramSocket(12345);

// 创建接收数据包对象
byte[] bys = new byte[1024];
DatagramPacket dp = new DatagramPacket(bys, bys.length);

// 接收数据包
ds.receive(dp);

// 解析数据,并显示在控制台
String ip = dp.getAddress().getHostAddress();
String s = new String(dp.getData(), 0, dp.getLength());
System.out.println("from" + ip + " data is:" + s);

// 释放资源
ds.close();
}
}


package cn.itcast_03;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class SedDemo {
public static void main(String[] args) throws IOException {
// 创建发送端Socket对象
DatagramSocket ds = new DatagramSocket();

// 创建数据,并打包
byte[] bys = "helloworld".getBytes();
DatagramPacket dp = new DatagramPacket(bys, bys.length,
InetAddress.getByName("192.168.31.165"), 12345);

// 发送数据
ds.send(dp);

// 释放资源
ds.close();

}
}