Java_网络编程_使用UDP协议发送及接收数据

来源:互联网 发布:js多行注释 编辑:程序博客网 时间:2024/05/16 09:04
package test;import java.io.IOException;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;public class UDPSender {public static void main(String[] args) throws IOException {// 建立UDP的SocketDatagramSocket ds = new DatagramSocket(3333);// 将数据封装到数据包中。数据包对象是DatagramPacketString text = "Hello UDP";byte[] buf = text.getBytes();DatagramPacket dp = new DatagramPacket(buf, buf.length,InetAddress.getByName("127.0.0.1"), 10000);// 发送数据ds.send(dp);// 关闭资源ds.close();}}



package test;import java.io.IOException;import java.net.DatagramPacket;import java.net.DatagramSocket;public class UDPReceiver {public static void main(String[] args) throws IOException {// 建立UDP的SocketDatagramSocket ds = new DatagramSocket(10000);byte[] buf = new byte[1024];DatagramPacket dp = new DatagramPacket(buf, buf.length);ds.receive(dp);// 阻塞// 解析数据包的内容String ip = dp.getAddress().getHostAddress();int port = dp.getPort();String text = new String(dp.getData(), 0, dp.getLength());System.out.println(ip + ":" + port + ":" + text);ds.close();}}
输出:

127.0.0.1:3333:Hello UDP

0 0