网络编程-UDP2
1 package com.yyq; 2 3 import java.io.BufferedReader; 4 import java.io.InputStreamReader; 5 import java.net.DatagramPacket; 6 import java.net.DatagramSocket; 7 import java.net.InetAddress; 8 import java.net.SocketException; 9 10 public class UdpSend2 { 11 public static void main(String[] args) throws Exception { 12 //1. 创建服务 13 DatagramSocket ds = new DatagramSocket(5555); 14 //2.从键盘中录入数据 15 BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in)); 16 String line = null; 17 while((line = bufr.readLine())!=null){ 18 if("88".equals(line)){ 19 break; 20 } 21 byte[] buf = line.getBytes(); 22 DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getLocalHost(),10001); 23 ds.send(dp); 24 //ds.close(); 25 } 26 } 27 } 28 29 30 31 32 package com.yyq; 33 34 import java.io.IOException; 35 import java.net.DatagramPacket; 36 import java.net.DatagramSocket; 37 import java.net.SocketException; 38 39 public class UdpRece2 { 40 public static void main(String[] args) throws Exception { 41 DatagramSocket ds = new DatagramSocket(10001); 42 while(true){ 43 byte[] buf = new byte[1024]; 44 DatagramPacket dp = new DatagramPacket(buf,buf.length); 45 ds.receive(dp); 46 String ip = dp.getAddress().getHostAddress(); 47 String data = new String(dp.getData(),0,dp.getLength()); 48 System.out.println(ip + ":" + data +":"+dp.getPort()); 49 System.out.println("haode"); 50 } 51 } 52 }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步