首页 > 代码库 > UDP学习3(通过键盘录入方式发送数据demo)

UDP学习3(通过键盘录入方式发送数据demo)

 1 import java.net.*; 2 import java.io.*; 3 class UDPSDemo 4 { 5     public static void main(String[]args) throws Exception 6     { 7         //创建发送端socket服务 8         DatagramSocket ds=new DatagramSocket(); 9         //准备发送的数据包10         BufferedReader br=new BufferedReader(new InputStreamReader(System.in));11         String line;12         while((line=br.readLine())!=null)13         {14             if("886".equals(line))15                 break;16             byte[] buf=line.getBytes();17             //数据包18             DatagramPacket dp=new DatagramPacket(buf,buf.length,InetAddress.getByName("localhost"),10000);19             //发送20             ds.send(dp);21         }22         ds.close();23     }24 }25 26 class UDPRDemo27 {28     public static void main(String[]args) throws Exception29     {30         //创建接收端socket服务,明确监听端口号31         DatagramSocket ds=new DatagramSocket(10000);32         while(true)33         {34             //准备接收数据的数据包35             byte[] buf=new byte[1024];36             DatagramPacket dp=new DatagramPacket(buf,buf.length);37                         //接收38             ds.receive(dp);39             String address=dp.getAddress().getHostAddress();40             String data=http://www.mamicode.com/new String(dp.getData(),0,dp.getLength());41             System.out.println("IP:"+address);42             System.out.println("Data:"+data);43         }44     }45 }    
View Code

 

UDP学习3(通过键盘录入方式发送数据demo)