java 网络编程(二)----UDP基础级的示例

      下面介绍UDP基础级的代码示例:

首先了解创建UDP传输的发送端的思路:

1.创建UDP的Socket服务。
2.将要发送的数据封装到数据包中。
3.通过UDP的socket服务将数据包发送出去。
4.关闭socket服务。

而接收端的思想如下:

1.创建UDP的Socket服务。需要明确一个端口号。
2.创建数据包,用于存储接收到的数据,方便用数据包对象的方法解析各种数据。
3.使用socket服务的recive方法将接收到的数据存储到数据包中。
4.通过数据包中的方法解析数据包中的数据。
5.关闭资源。

具体代码如下:

//发送端

public class UDPSendDemo {

public static void main(String[] args) throws IOException {

System.out.println("发送端启动。。。。。");

//1. UDP的Socket服务,使用DatagramSocket对象,可以指定一个端口进行发送,否则服务器会默认选一个未被使用的端口
DatagramSocket da = new DatagramSocket(9999);

//2. 将要发送的数据封装到数据包中。使用DatagramPacket将发送数据封装在里面
String str="UD发送数据演示";
byte[] buf=str.getBytes();
//定义了接收方的IP地址和端口
DatagramPacket dp= new DatagramPacket(buf, buf.length,InetAddress.getByName("192.168.5.163"),10000);

//3.通过UDP的socket服务将DatagramPacket数据包发送出去,使用send方法
da.send(dp);

//4.资源使用完,关闭资源
da.close();
}
}

// 接收端

public class UDPReciveDemo {

public static void main(String[] args) throws IOException {

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.使用socket服务的recive方法将接收到的数据存储到数据包中。
ds.receive(dp);

//4.通过数据对象中的方法解析数据包中的数据。比如:IP地址,端口,内容
String ipString=dp.getAddress().getHostAddress();
int port =dp.getPort();
String data= new String(dp.getData(),0,dp.getLength());

System.out.println("ip :"+ipString+" "+"port :"+port+" "+"data :"+data);

// 5.关闭资源
ds.close();
}
}

原文地址:https://www.cnblogs.com/loleina/p/5174679.html