package com.sxt.udp; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress; import java.net.SocketException; public class UdpClient { public static void main(String[] args) throws Exception { System.out.println("客户端启动中......."); //使用DatagramSocket DatagramSocket client = new DatagramSocket(8888); String str=new String("你好呀呀,UDP"); byte[] datas = str.getBytes(); DatagramPacket packet = new DatagramPacket(datas,0, datas.length, new InetSocketAddress("127.0.0.1",9999)); client.send(packet); client.close(); } }
package com.sxt.udp; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress; public class UdpServer { public static void main(String[] args) throws Exception { System.out.println("接收端启动中......."); //使用DatagramSocket DatagramSocket server = new DatagramSocket(9999); byte[] datas = new byte[1024*60]; DatagramPacket packet = new DatagramPacket(datas,0, datas.length); server.receive(packet); datas = packet.getData(); System.out.println(new String(datas,0,datas.length)); server.close(); } }
运行结果:(先启动服务器,再启动客户端)
原文地址:https://www.cnblogs.com/nihaoya-czw/p/10353486.html
时间: 2024-11-10 08:35:52