/**
* java 后端爱好者 --------小玉玉
* 不定时发布,实际已处理OK的 文章
*/
// UDP 网络 发送方
public class UDPClient {
public static String ip = "127.0.0.1"; //ip
public static int port = 999; //端口
public static void sendMsgToAgent(byte[] buf) {
try {
DatagramSocket ds = new DatagramSocket();//通过DatagramSocket对象创建udp服务
DatagramPacket dp =
new DatagramPacket(buf, buf.length, InetAddress.getByName(ip), port);//发送至指定IP,指定端口
ds.send(dp);//通过send方法将数据包发送出去
ds.close();//关闭资源
System.out.println("UDP send msg :" + CommonUtils.bytesToHexString(buf));
} catch (Exception exception) {
exception.printStackTrace(); //输出出错信息
}
}
public static void sendTest() {
String sMsg = "小玉玉, 你好";
// 转换 字节数组
byte[] message = CommonUtils.hexStringToBytes(sMsg); //发送信息
sendMsgToAgent(message);
}
}
/**
* 接收方
* 启动时 必须先初始化 .start(); 启动初始化
*/
public class UDPServer extends Thread {
int port=999; //端口
DatagramSocket ds=null;
@Override
public void run(){
try{
init(); //初始化
}
catch (Exception exception){
exception.printStackTrace(); //输出出错信息
return;
}
receive();
}
public void init() throws IOException {
ds = new DatagramSocket(port);//创建数据报套接字并将其绑定到本地主机上的指定端口
}
public void receive(){
while(true)
{
//定义数据包,用于存储数据
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf,buf.length);
try {
ds.receive(dp);//通过服务的receive方法将收到数据存入数据包中,receive()为阻塞式方法
}
catch (IOException e) {
e.printStackTrace();
}
//通过数据包的方法获取其中的数据
String data = new String(dp.getData(),0,dp.getLength());
System.out.println("UDP server receive :"+ CommonUtils.bytesToHexString(buf));
System.out.println("接收的信息---: " + data); // 小玉玉, 你好
}
}
}
简单的UDP本地收发
最新推荐文章于 2023-06-24 14:49:15 发布