JAVA_UDP

 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 }

时间: 2024-10-05 20:32:32

JAVA_UDP的相关文章