public static void send(String ip,String MSG_CONTENT ) {
DatagramSocket socket;
InetAddress address;
long IPMSG_SENDMSG = 0x00000020;
String SENDER = "乱 7 8 糟";
String HOST = "Localhost";
try {
socket = new DatagramSocket();
address = InetAddress.getByName(ip);// 发送给消息的地址
byte[] buffer = ("1:" + new Date().getTime() + ":" + SENDER + ":"
+ HOST + ":" + IPMSG_SENDMSG + ":" + MSG_CONTENT)
.getBytes("gbk");
DatagramPacket packet = new DatagramPacket(buffer, buffer.length,
address, 2425);
socket.send(packet); // 发送报文
packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);// 接收回应
String message = new String(packet.getData()); // 得到报文信息
System.out.println(message); // 显示对方返回的信息
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
java向飞秋发送提示消息(转载预留,方法可以包装打成jar包用)
最新推荐文章于 2024-12-02 22:01:41 发布
本文介绍如何使用Java的DatagramSocket类进行UDP协议的数据包发送与接收,包括构造数据包、发送与接收流程及异常处理。
2万+

被折叠的 条评论
为什么被折叠?



