扫一扫
分享文章到微信
扫一扫
关注官方公众号
至顶头条
在本页阅读全文(共4页)
Listing 5: DGSServer.java // DGSServer.java import java.io.*; import java.net.*; class DGSServer { public static void main (String [] args) throws IOException { System.out.println ("Server starting ...\n"); // Create a datagram socket bound to port 10000. Datagram // packets sent from client programs arrive at this port. DatagramSocket s = new DatagramSocket (10000); // Create a byte array to hold data contents of datagram // packet. byte [] data = new byte [100]; // Create a DatagramPacket object that encapsulates a reference // to the byte array and destination address information. The // DatagramPacket object is not initialized to an address // because it obtains that address from the client program. DatagramPacket dgp = new DatagramPacket (data, data.length); // Enter an infinite loop. Press Ctrl+C to terminate program. while (true) { // Receive a datagram packet from the client program. s.receive (dgp); // Display contents of datagram packet. System.out.println (new String (data)); // Echo datagram packet back to client program. s.send (dgp); } } } |
Listing 6: MCClient.java // MCClient.java import java.io.*; import java.net.*; class MCClient { public static void main (String [] args) throws IOException { // Create a MulticastSocket bound to local port 10000. All // multicast packets from the server program are received // on that port. MulticastSocket s = new MulticastSocket (10000); // Obtain an InetAddress object that contains the multicast // group address 231.0.0.1. The InetAddress object is used by // DatagramPacket. InetAddress group = InetAddress.getByName ("231.0.0.1"); // Join the multicast group so that datagram packets can be // received. s.joinGroup (group); // Read several datagram packets from the server program. for (int i = 0; i < 10; i++) { // No line will exceed 256 bytes. byte [] buffer = new byte [256]; // The DatagramPacket object needs no addressing // information because the socket contains the address. DatagramPacket dgp = new DatagramPacket (buffer, buffer.length); // Receive a datagram packet. s.receive (dgp); // Create a second byte array with a length that matches // the length of the sent data. byte [] buffer2 = new byte [dgp.getLength ()]; // Copy the sent data to the second byte array. System.arraycopy (dgp.getData (), 0, buffer2, 0, dgp.getLength ()); // Print the contents of the second byte array. (Try // printing the contents of buffer. You will soon see why // buffer2 is used.) System.out.println (new String (buffer2)); } // Leave the multicast group. s.leaveGroup (group); // Close the socket. s.close (); } } |
如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。
现场直击|2021世界人工智能大会
直击5G创新地带,就在2021MWC上海
5G已至 转型当时——服务提供商如何把握转型的绝佳时机
寻找自己的Flag
华为开发者大会2020(Cloud)- 科技行者