udp 是一种网络 传输协议,示例如下:
//udp发送端
private void text1() {
/*
* 创建udp服务 的发送端
* 1,建立udp的 socket服务
* 2,将发送的数据放入 数据包中
* 3,通过udp的socket服务把 数据包发送出去
* 4,关闭socket服务
* */
DatagramSocket dataSocket = null;
try {
dataSocket = new DatagramSocket();
String str = "你好!";
DatagramPacket packet = new DatagramPacket(str.getBytes(), 0);
packet.setAddress(InetAddress.getByName("ip地址"));
packet.setPort(8080);
dataSocket.send(packet);
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
dataSocket.close();
}
//udp接收端
private void text2() {
/*
* 1,建立udp 的socket服务,需要绑定本地的一个端口
* 2,创建数据包 用于接收数据
* 3,使用socket的receive方法 接收数据,并存储到数据包中
* 4,取出并解析数据包中的数据
* */
StringBuffer str = new StringBuffer();
byte[] arr = new byte[1024];
DatagramSocket dataSocket = null;
try {
dataSocket = new DatagramSocket(8080);
DatagramPacket packet = new DatagramPacket(arr, arr.length);
//循环接受消息
while (true) {
//阻塞式
dataSocket.receive(packet);
String address = packet.getAddress().getHostAddress();
str.append(address.getBytes());
System.out.print("接受到来自" + address);
System.out.print("数据=" + str.toString());
}
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
dataSocket.close();
}