码迷,mamicode.com
首页 > 其他好文 > 详细

UDP 端到端

时间:2017-07-03 18:10:56      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:color   bytes   byte   package   java.net   packet   str   pre   接收   

 

 

 1 package UDP;
 2 
 3 import java.io.IOException;
 4 import java.net.DatagramPacket;
 5 import java.net.DatagramSocket;
 6 import java.net.InetAddress;
 7 import java.net.SocketException;
 8 import java.net.UnknownHostException;
 9 
10 public class Demo1 {
11 
12     public static void main(String[] args) throws IOException {
13         
14         DatagramSocket socket = new DatagramSocket();
15     
16         String str = "hello";
17         // 打包封装
18         DatagramPacket packet = new DatagramPacket(str.getBytes(), str.length(), InetAddress.getByName("localhost"),
19                 8000);
20         socket.send(packet);// 发送
21 
22         // 接收
23 
24         byte[] buff = new byte[100];
25         DatagramPacket packet2 = new DatagramPacket(buff, 100);
26         socket.receive(packet2);
27         System.out.println(new String(buff, 0, packet2.getLength()));
28         socket.close();
29     }
30 
31 }

 

 

 1 package UDP;
 2 
 3 import java.io.IOException;
 4 import java.net.DatagramPacket;
 5 import java.net.DatagramSocket;
 6 import java.net.InetAddress;
 7 import java.net.SocketException;
 8 
 9 public class Demo2 {
10 
11     public static void main(String[] args) throws IOException {
12         //接收
13         DatagramSocket socket = new DatagramSocket(8000);
14         byte[] buff = new byte[100];
15         DatagramPacket packet = new DatagramPacket(buff, 100);
16         socket.receive(packet);
17         System.out.println(new String (buff,0,packet.getLength()));
18 
19         //发送
20         String str = "me too";
21         DatagramPacket packet2 = new DatagramPacket(str.getBytes(), str.length(), packet.getAddress(),
22                 packet.getPort());
23         socket.send(packet2);
24         socket.close();
25 
26     }
27 
28 }

 

UDP 端到端

标签:color   bytes   byte   package   java.net   packet   str   pre   接收   

原文地址:http://www.cnblogs.com/the-wang/p/7112272.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!