Java套接字编程(下)(3)

王朝java/jsp·作者佚名  2008-05-31
宽屏版  字体: |||超大  

多点传送和MulticastSocket类

前面的例子显示了服务器程序线程发送单一的消息(通过流套接字或自寻址套接字)给唯一的客户端程序,这种行为被称为单点传送(unicasting),多数情况都不适合于单点传送,比如,摇滚歌手举办一场音乐会将通过互联网进行播放,画面和声音的质量依靠于传输速度,服务器程序要传送大约10亿字节的数据给客户端程序,使用单点传送,那么每个客户程序都要要复制一份数据,假如,互联网上有10000个客户端要收看这个音乐会,那么服务器程序通过Internet要传送10000G的数据,这必然导致网络阻塞,降低网络的传输速度。

假如服务器程序要将同一信息发送给多个客户端,那么服务器程序和客户程序可以利用多点传送(multicasting)方式进行通信。多点传送就是服务程序对专用的多点传送组的IP地址和端口发送一系列自寻址数据包,通过加入操作IP地址被多点传送Socket注册,通过这个点客户程序可以接收发送给组的自寻址包(同样客户程序也可以给这个组发送自寻址包),一旦客户程序读完所有要读的自寻址数据包,那么可以通过离开组操作离开多点传送组。

注重:IP地址224.0.0.1 到 239.255.255.255(包括)均为保留的多点传送组地址。

网络API通过MulticastSocket类和MulticastSocket,以及一些辅助类(比如NetworkInterface)支持多点传送,当一个客户程序要加入多点传送组时,就创建一个MulticastSocket对象。MulticastSocket(int port)构造函数答应应用程序指定端口(通过port参数)接收自寻址包,端口必须与服务程序的端口号相匹配,要加入多点传送组,客户程序调用两个joinGroup()方法中的一个,同样要离开传送组,也要调用两个leaveGroup()方法中的一个。

由于MulticastSocket扩展了DatagramSocket类,一个MulticastSocket对象就有权访问DatagramSocket方法。

List6是MCClient的源代码,这段代码示范了一个客户端加入多点传送组的例子。

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 ()];

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有