udp协议发送消息案例
1、创建UdpServer(udp服务器端)
package com.cppdy.udp; import java.net.DatagramPacket;
import java.net.DatagramSocket; //udp服务器端
public class UdpServer { public static void main(String[] args) throws Exception {
System.out.println("udp服务启动……");
DatagramSocket ds = new DatagramSocket(8080); byte[] buf = new byte[1024]; DatagramPacket dp = new DatagramPacket(buf, buf.length); ds.receive(dp); String add = dp.getAddress().toString(); String data = new String(dp.getData(), 0, dp.getLength()); System.out.println("服务器接受:从IP" + add + "传输的数据:" + data);
} }
2、创建UdpClient(udp客户端)
package com.cppdy.udp; import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress; //udp客户端
public class UdpClient { public static void main(String[] args) throws Exception { String msg = "吹泡泡的魚";
DatagramSocket ds = new DatagramSocket();
byte[] bytes = msg.getBytes(); DatagramPacket dp = new DatagramPacket(bytes, bytes.length, new InetSocketAddress("127.0.0.1", 8080)); ds.send(dp); ds.close(); System.out.println("客户端发送信息完毕……");
} }