UDP通讯协议实现接收和发送数据
作者:
Agoni7z
,
2024-05-07 20:55:05
,
所有人可见
,
阅读 15
receive
package com.itheima.A03_updatedemo1;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class ReceiveMessage {
public static void main(String[] args) throws IOException {
DatagramSocket ds = new DatagramSocket(10086);
byte[] bytes = new byte[1024];
DatagramPacket dp = new DatagramPacket(bytes, bytes.length);
while (true) {
ds.receive(dp);
//3. 解析数据包
byte[] data = dp.getData();
int len = dp.getLength();
String ip = dp.getAddress().getHostName();
String name = dp.getAddress().getHostName();
System.out.println("ip为: " + ip + " 主机名为: " + name + "的人,发送了数据:" + new String(data, 0, len));
}
}
}
sent
package com.itheima.A03_updatedemo1;
import javax.print.DocFlavor;
import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
public class sentMessageDemo2 {
public static void main(String[] args) throws IOException {
//UDP发送数据:数据来自键盘录入,直到输入的数据是886,发送数据结束
//UDP接收数据:因为接收端不知道发送端什么时候停止发送,故采用死循环接收
//1. 创建DatagramSocket的对象
DatagramSocket ds = new DatagramSocket();
//2. 打包数据
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("请输入您要说的话:");
String str = sc.nextLine();
if (str.equals("886")) {
break;
}
byte[] bytes = str.getBytes();
InetAddress address = InetAddress.getByName("127.0.0.1");
int port = 10086;
DatagramPacket dp = new DatagramPacket(bytes, bytes.length, address, port);
//3.发送数据
ds.send(dp);
}
// 4. 释放资源
ds.close();
}
}