Java 网络编程(六)UDP
UDP
发短信:不用连接,需要知道对方的地址
客户端:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | //不需要连接服务器 public class UdpClientDemo01 { public static void main(String[] args) throws Exception{ //1.建立一个Socket DatagramSocket socket = new DatagramSocket(); //2.建个包 String msg = "你好啊!" ; //发送给谁 InetAddress localhost = InetAddress.getByName( "localhost" ); int port = 9090 ; DatagramPacket datagramPacket = new DatagramPacket(msg.getBytes(), 0 ,msg.getBytes().length,localhost,port); //3.发送包 socket.send(datagramPacket); //4.关闭流 socket.close(); } } |
接收端:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | //还要等待客户端的连接 public class UdpServerDemo01 { public static void main(String[] args) throws Exception{ //开放端口 DatagramSocket socket = new DatagramSocket( 9090 ); //接收数据 byte [] buffer = new byte [ 1024 ]; DatagramPacket datagramPacket = new DatagramPacket(buffer, 0 , buffer.length); socket.receive(datagramPacket); //阻塞接受 System.out.println(datagramPacket.getAddress().getHostAddress()); //关闭连接 socket.close(); } } |
循环接收消息:
发送方:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public class UdpSenderDemo01 { public static void main(String[] args) throws Exception{ DatagramSocket socket = new DatagramSocket( 8888 ); //准备数据;控制台读取System.in BufferedReader reader = new BufferedReader( new InputStreamReader(System.in)); while ( true ) { String data = reader.readLine(); byte [] datas = data.getBytes(); DatagramPacket packet = new DatagramPacket(datas, 0 , datas.length, new InetSocketAddress( "localhost" , 6666 )); socket.send(packet); if (data.equals( "bye" )){ break ; } } socket.close(); } } |
接收方:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public class UdpReceiveDemo01 { public static void main(String[] args) throws Exception { DatagramSocket socket = new DatagramSocket( 6666 ); while ( true ){ //准备接收包裹 byte [] container = new byte [ 1024 ]; DatagramPacket packet = new DatagramPacket(container, 0 ,container.length); //断开连接 byte [] data = packet.getData(); String receiveData = new String(data, 0 ,data.length); System.out.println(receiveData); if (receiveData.equals( "bye" )){ break ; } } socket.close(); } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧