发送端:
public class SendDemo
{
public static void main(String[] args) throws IOException
{
/*
* 创建UDP发送端的步骤
* 1,创建UDP的socket服务
* 2,将要发送的数据封装在数据包中
* 3,通过UDP的socket服务将数据包发送出去
* 4,关闭socket资源
*/
System.out.println("发送端启动...");
//创建UDP的socket服务
DatagramSocket ds = new DatagramSocket();
//将要发送的数据封装在数据包中
String str = "连接上了偶";
byte[] buf = str.getBytes();
DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress.getByName("127.0.0.1"), 10000);
//通过UDP的socket服务将数据包发送出去 使用send方法
ds.send(dp);
//关闭资源
ds.close();
}
}
接收端:
public class ReceiveDemo
{
public static void main(String[] args) throws IOException
{
/*
* 创建UDP的接收端
* 1,建立UDP的socket服务
* 2,创建数据包用于存储接收到的数据 方便使用数据包对象的方法来解析这些数据
* 3,通过socket的receive方法接收数据存储到数据包中
* 4,通过数据包对象的方法解析数据包中的资源
* 5,关闭资源
*/
System.out.println("接收端启动...");
//1,建立UDP的socket服务
DatagramSocket ds = new DatagramSocket(10000);
//2,创建数据包
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, buf.length);
//3,使用接收方法来将数据存储到数据包中
ds.receive(dp);
//4,通过数据包对象的方法解析数据包的数据(地址 端口 数据内容)
String ip = dp.getAddress().getHostAddress();
int port = dp.getPort();
String text = new String(dp.getData(),0,dp.getLength());
//5,关闭资源
ds.close();
System.out.println(ip+":"+port+":"+text);
}
}