个字节数组buffer 和 buffer2感到奇怪,当接收到一个自寻址包后,getData()方法返回一个引用,自寻址包的长度是256个字节,如果要输出所有数据,在输出完实际数据后会有很多空格,这显然是不合理的,所以我们必须去掉这些空格,因此我们创建一个小的字节数组buffer2,buffer2的实际长度就是数据的实际长度,通过调用DatagramPacket''s getLength()方法来得到这个长度。从buffer 到 buffer2快速复制getLength()的长度的方法是调用System.arraycopy()方法。
List7 MCServer的源代码显示了服务程序是怎样工作的。
Listing 7: MCServer.java
// MCServer.java
import java.io.*;
import java.net.*;
class MCServer
{
public static void main (String[] args) throws IOException
{
System.out.println ("Server starting...\n");
// Create a MulticastSocket not bound to any port.
MulticastSocket s = new MulticastSocket ();
// Because MulticastSocket subclasses DatagramSocket, it is
// legal to replace MulticastSocket s = new MulticastSocket ();
// with the following line.
// DatagramSocket s = new DatagramSocket ();
// 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");
// Create a DatagramPacket object that encapsulates a reference
// to a byte array (later) and destination address
// information. The destination address consists of the
// multicast group address (as stored in the InetAddress object)
// and port number 10000 -- the port to which multicast datagram
// packets are sent. (Note: The dummy array is used to prevent a
// NullPointerException object being thrown from the
// DatagramPacket constructor.)
byte [] dummy = new byte [0];
DatagramPacket dgp = new DatagramPacket (dummy,
0,
group,
10000);
// Send 30000 Strings to the port.
for (int i = 0; i < 30000; i++)
{
// Create an array of bytes from a String. The platform''s
// default character set is used to convert from Unicode
// characters to bytes.
byte [] buffer = ("Video line " + i).getBytes ();
// Establish the byte array as the datagram packet''s
// buffer.
dgp.setData (buffer);
// Establish the byte array''s length as the length of the
// datagram packet''s buffer.
dgp.setLength (buffer.length);
// Send the datagram to all members of the multicast group
// that listen on port 10000.
s.send (dgp);
}
// Close the socket.
s.close ();
}
}
MCServer创建了一个MulticastSocket对象,由于他是DatagramPacket对象的一部分,所以他没有绑定端口号,DatagramPacket有多点传送组的IP地址(231.0.0.0),一旦创建DatagramPacket对象,MCServer就进入一个发送30000条的文本的循环中,对文本的每一行均要创建一个字节数组,他们的引用均存储在前面创建的DatagramPacket对象中,通过send()方法,自寻址包发送给所有的组成员。
在编译了MCServer 和 MCClient后,通 |