请求方法
public static String sendUdpMessage(String host, Integer port, String message) throws Exception {
String replyMessage = "";
if (StringUtils.isEmpty(host)) {
host = "127.0.0.1";
}
DatagramSocket socket = new DatagramSocket(8091);
byte[] buf = message.getBytes();
//将数据打包
DatagramPacket packet = new DatagramPacket(buf, buf.length, InetAddress.getByName(host), port);
socket.send(packet);
try {
//设置超时时间
socket.setSoTimeout(1000);
byte[] data =new byte[1024];
DatagramPacket packet1 = new DatagramPacket(data,data.length);
socket.receive(packet1);
replyMessage = new String(data,0,packet1.getLength());
} catch (Exception e) {
e.printStackTrace();
replyMessage = "";
} finally {
socket.close();
}
return replyMessage;
}