首页 > 编程语言 > 详细

Java UDP协议传输

时间:2017-12-14 18:59:37      阅读:204      评论:0      收藏:0      [点我收藏+]

使用UDP协议编写一个网络程序,设置接收端程序的监听端口是8001,发送端发送的数据是“Hello, world‘’.

 

接收端:

 1 import java.net.*;
 2 public class example {
 3 
 4     public static void main(String[] args) throws Exception 
 5         {
 6             byte[] buf=new byte[1024];
 7             DatagramSocket ds=new DatagramSocket(8001);
 8             DatagramPacket dp=new DatagramPacket(buf,1024);
 9             System.out.println("等待接受数据");
10             ds.receive(dp);
11              String str=new String(dp.getData());
12                 System.out.println(str);  
13                 ds.close(); 
14         }
15 
16     }

发送端:

 1 import java.net.*;  
 2 public class example1 {  
 3   
 4     public static void main(String[] args) throws Exception{  
 5         DatagramSocket ds=new DatagramSocket(3000);     
 6         String str="Hello, world";           
 7         DatagramPacket dp=new DatagramPacket(str.getBytes(), str.length(),InetAddress.getByName("localhost"),8001);
 8         System.out.println("发送消息");  
 9         ds.send(dp);   
10         ds.close();    
11     }  
12 }  

 运行结果:

技术分享图片

技术分享图片

 

Java UDP协议传输

原文:http://www.cnblogs.com/songqinzhe/p/8039071.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!