JAVA_UDP

时间:2015-05-16 01:22:15   收藏:0   阅读:153

技术分享

 1 import java.net.*;
 2 import java.io.*;
 3 
 4 public class TestUDPServer
 5 {
 6     public static void main(String args[]) throws Exception
 7     {
 8         byte buf[] = new byte[1024];
 9         DatagramPacket dp = new DatagramPacket(buf, buf.length);
10         DatagramSocket ds = new DatagramSocket(5678);
11         while(true)
12         {
13             ds.receive(dp);
14             ByteArrayInputStream bais = new ByteArrayInputStream(buf);
15             DataInputStream dis = new DataInputStream(bais);
16             System.out.println(dis.readLong());
17         }
18     }
19 }

 

 1 import java.net.*;
 2 import java.io.*;
 3 
 4 public class TestUDPClient
 5 {
 6     public static void main(String args[]) throws Exception
 7     {
 8         long n = 10000L;
 9         ByteArrayOutputStream baos = new ByteArrayOutputStream();
10         DataOutputStream dos = new DataOutputStream(baos);
11         dos.writeLong(n);
12         
13         byte[] buf = baos.toByteArray();
14 System.out.println(buf.length);
15         
16         DatagramPacket dp = new DatagramPacket(buf, buf.length, 
17                                                new InetSocketAddress("127.0.0.1", 5678)
18                                                );
19         DatagramSocket ds = new DatagramSocket(9999);
20         ds.send(dp);
21         ds.close();
22         
23     }
24 }

 

技术分享

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!