Java套接字编程(下)

自寻址套接字(Datagram Sockets)

  因为使用流套接字的每个连接均要花费一定的时间,要减少这种开销,网络API提供了第二种套接字:自寻址套接字(datagram socket),自寻址使用UDP发送寻址信息(从客户程序到服务程序或从服务程序到客户程序),不同的是可以通过自寻址套接字发送多IP信息包,自寻址信息包含在自寻址包中,此外自寻址包又包含在IP包内,这就将寻址信息长度限制在60000字节内。图2显示了位于IP包内的自寻址包的自寻址信息。


  与TCP保证信息到达信息目的地的方式不同,UDP提供了另外一种方法,如果自寻址信息包没有到达目的地,,那么UDP也不会请求发送者重新发送自寻址包,这是因为UDP在每一个自寻址包中包含了错误检测信息,在每个自寻址包到达目的地之后UDP只进行简单的错误检查,如果检测失败,UDP将抛弃这个自寻址包,也不会从发送者那里重新请求替代者,这与通过邮局发送信件相似,发信人在发信之前不需要与收信人建立连接,同样也不能保证信件能到达收信人那里

  自寻址套接字工作包括下面三个类:DatagramPacket, DatagramSocket,和 MulticastSocket。DatagramPacket对象描绘了自寻址包的地址信息,DatagramSocket表示客户程序和服务程序自寻址套接字,MulticastSocket描绘了能进行多点传送的自寻址套接字,这三个类均位于java.net包内。

  DatagramPacket类

  在使用自寻址包之前,你需要首先熟悉DatagramPacket类,地址信息和自寻址包以字节数组的方式同时压缩入这个类创建的对象中

  DatagramPacket有数个构造函数,即使这些构造函数的形式不同,但通常情况下他们都有两个共同的参数:byte [] buffer 和 int length,buffer参数包含了一个对保存自寻址数据包信息的字节数组的引用,length表示字节数组的长度。

  最简单的构造函数是DatagramPacket(byte [] buffer, int length),这个构造函数确定了自寻址数据包数组和数组的长度,但没有任何自寻址数据包的地址和端口信息,这些信息可以后面通过调用方法setAddress(InetAddress addr)和setPort(int port)添加上,下面的代码示范了这些函数和方法。

byte [] buffer = new byte [100];
DatagramPacket dgp = new DatagramPacket (buffer, buffer.length);
InetAddress ia = InetAddress.getByName ("www.disney.com");
dgp.setAddress (ia);
dgp.setPort (6000); // Send datagram packet to port 6000.

  如果你更喜欢在调用构造函数的时候同时包括地址和端口号,可以使用DatagramPacket(byte [] buffer, int length, InetAddress addr, int port)函数,下面的代码示范了另外一种选择。

byte [] buffer = new byte [100];
InetAddress ia = InetAddress.getByName ("www.disney.com");
DatagramPacket dgp = new DatagramPacket (buffer, buffer.length, ia,
6000);

  有时候在创建了DatagramPacket对象后想改变字节数组和他的长度,这时可以通过调用setData(byte [] buffer) 和 setLength(int length)方法来实现。在任何时候都可以通过调用getData() 来得到字节数组的引用,通过调用getLength()来获得字节数组的长度。下面的代码示范了这些方法:

byte [] buffer2 = new byte [256];
dgp.setData (buffer2);
dgp.setLength (buffer2.length);


  关于DatagramPacket的更多信息请参考SDK文档。

DatagramSocket类

  DatagramSocket类在客户端创建自寻址套接字与服务器端进行通信连接,并发送和接受自寻址套接字。虽然有多个构造函数可供选择,但我发现创建客户端自寻址套接字最便利的选择是DatagramSocket()函数,而服务器端则是DatagramSocket(int port)函数,如果未能创建自寻址套接字或绑定自寻址套接字到本地端口,那么这两个函数都将抛出一个SocketException对象,一旦程序创建了DatagramSocket对象,那么程序分别调用send(DatagramPacket dgp)和 receive(DatagramPacket dgp)来发送和接收自寻址数据包,

  List4显示的DGSClient源代码示范了如何创建自寻址套接字以及如何通过套接字处理发送和接收信息

Listing 4: DGSClient.java
// DGSClient.java

import java.io.*;
import java.net.*;

class DGSClient
{
 public static void main (String [] args)
 {
  String host = "localhost";

  // If user specifies a command-line argument, that argument
  // represents the host name.
 
  if (args.length == 1)
   host = args [0];

  DatagramSocket s = null;

  try
  {
   // Create a datagram socket bound to an arbitrary port.

   s = new DatagramSocket ();

   // Create a byte array that will hold the data portion of a
   // datagram packet's message. That message originates as a
   // String object, which gets converted to a sequence of
   // bytes when String's getBytes() method is called. The
   // conversion uses the platform's default character set.

   byte [] buffer;
   buffer = new String ("Send me a datagram").getBytes ();

   // Convert the name of the host to an InetAddress object.
   // That object contains the IP address of the host and is
   // used by DatagramPacket.

   InetAddress ia = InetAddress.getByName (host);

   // Create a DatagramPacket object that encapsulates a
   // reference to the byte array and destination address
   // information. The destination address consists of the
   // host's IP address (as stored in the InetAddress object)
   // and port number 10000 -- the port on which the server
   // program listens.

   DatagramPacket dgp = new DatagramPacket (buffer,
        buffer.length,
        ia,
        10000);

   // Send the datagram packet over the socket.

   s.send (dgp);

   // Create a byte array to hold the response from the server.
   // program.

   byte [] buffer2 = new byte [100];

   // Create a DatagramPacket object that specifies a buffer
   // to hold the server program's response, the IP address of
   // the server program's computer, and port number 10000.

   dgp = new DatagramPacket (buffer2,
      buffer.length,
      ia,
      10000);

   // Receive a datagram packet over the socket.

   s.receive (dgp);

   // Print the data returned from the server program and stored
   // in the datagram packet.

   System.out.println (new String (dgp.getData ()));

  }
  catch (IOException e)
  {
   System.out.println (e.toString ());
  }
  finally
  {
   if (s != null)
    s.close (); 
  }
 }
}


  DGSClient由创建一个绑定任意本地(客户端)端口好的DatagramSocket对象开始,然后装入带有文本信息的数组buffer和描述服务器主机IP地址的InetAddress子类对象的引用,接下来,DGSClient创建了一个DatagramPacket对象,该对象加入了带文本信息的缓冲器的引用,InetAddress子类对象的引用,以及服务端口号10000, DatagramPacket的自寻址数据包通过方法sent()发送给服务器程序,于是一个包含服务程序响应的新的DatagramPacket对象被创建,receive()得到响应的自寻址数据包,然后自寻址数据包的getData()方法返回该自寻址数据包的一个引用,最后关闭DatagramSocket。

  DGSServer服务程序补充了DGSClient的不足,List5是DGSServer的源代码:

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);
 }
}
}


  DGSServer创建了一个绑定端口10000的自寻址套接字,然后创建一个字节数组容纳自寻址信息,并创建自寻址包,下一步,DGSServer进入一个无限循环中以接收自寻址数据包、显示内容并将响应返回客户端,自寻址套接没有关闭,因为循环是无限的。

  在编译DGSServer 和DGSClient的源代码后,由输入java DGSServer开始运行DGSServer,然后在同一主机上输入Java DGSClient开始运行DGSClient,如果DGSServer与DGSClient运行于不同主机,在输入时注意要在命令行加上服务程序的主机名或IP地址,如:java DGSClient
www.yesky.com

多点传送和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 ()];

   // 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 ();
 }
}

  MCClient创建了一个绑定端口号10000的MulticastSocket对象,接下来他获得了一个InetAddress子类对象,该子类对象包含多点传送组的IP地址231.0.0.0,然后通过joinGroup(InetAddress addr)方法加入多点传送组中,接下来MCClient接收10个自寻址包,同时输出他们的内容,然后使用leaveGroup(InetAddress addr)方法离开传送组,最后关闭套接字。

  也许你对使用两个字节数组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.

   <img src='http://counter.yesky.com/counter.shtml?CID=72348977504190464&AID=1601474&refer=http%3A//blog.csdn.net/logic_202/archive/2005/07/03/411747.aspx&cur=http%3A//blog.csdn.net/logic_202/archive/2005/07/03/411777.aspx' border='0' alt='' width='0' height='0'> // 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后,通过输入java MCServer开始运行MCServer,最后再运行一个或多个MCClient。

  结论

  本文通过研究套接字揭示了Java的网络API的应用方法,我们介绍了套接自的慨念和套接字的组成,以及流套接字和自寻址套接字,以及如何使用InetAddress, Socket, ServerSocket, DatagramPacket, DatagramSocket和MulticastSocket类。在完成本文后就可以编写基本的底层通讯程序。

posted @ 2009-05-24 23:36  冷尘  阅读(214)  评论(0编辑  收藏  举报