This repository has been archived on 2025-09-14. You can view files and clone it, but cannot push or open issues or pull requests.
Files
nezha-olp-exporter/src/main/java/com/nis/util/UdpUtils.java

49 lines
1.6 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.nis.util;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class UdpUtils {
private static final Logger logger = LoggerFactory.getLogger(TextFormatUtils.class);
public static String send(String sendIp,Integer slot,int timeout) {
String rlt = "";
DatagramSocket ds = null;
try {
ds = new DatagramSocket();//通过DatagramSocket对象创建udp服务
ds.setSoTimeout(timeout);
// String line = "00 06 0502 00 00 68c2"; //发送的16进制字符串
String slotStr = slot+"";
if(slot<10) {
slotStr = "0"+slotStr;
}
String line = "00 "+slotStr+" 0502 00 00"; //发送的16进制字符串
byte[] buf = HexUtils.hexStringToByteArray(line);
DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName(sendIp),6800);//发送至指定IP指定端口
ds.send(dp);//通过send方法将数据包发送出去
//定义数据包,用于存储数据
byte[] buf2 = new byte[8];
DatagramPacket dp2 = new DatagramPacket(buf2,buf2.length);
ds.receive(dp2);//通过服务的receive方法将收到数据存入数据包中,receive()为阻塞式方法
//通过数据包的方法获取其中的数据
String ip = dp2.getAddress().getHostAddress();
System.out.println(ip+"::"+HexUtils.bytesToHexString(buf2));
rlt = HexUtils.bytesToHexString(buf2);
}catch (Exception e) {
logger.error(sendIp+"::"+slot+">>"+e.getMessage());
}finally {
if(ds!=null) {
ds.close();//关闭资源
}
}
return rlt;
}
}