自寻址套接字(Datagram Sockets)
因为使用流套接字的每个连接均要花费一定的时间要减少这种开销网络API提供了第二种套接字自寻址套接字(datagram socket)自寻址使用UDP发送寻址信息(从客户程序到服务程序或从服务程序到客户程序)不同的是可以通过自寻址套接字发送多IP信息包自寻址信息包含在自寻址包中此外自寻址包又包含在IP包内这就将寻址信息长度限制在字节内图显示了位于IP包内的自寻址包的自寻址信息
与TCP保证信息到达信息目的地的方式不同UDP提供了另外一种方法如果自寻址信息包没有到达目的地那么UDP也不会请求发送者重新发送自寻址包这是因为UDP在每一个自寻址包中包含了错误检测信息在每个自寻址包到达目的地之后UDP只进行简单的错误检查如果检测失败UDP将抛弃这个自寻址包也不会从发送者那里重新请求替代者这与通过邮局发送信件相似发信人在发信之前不需要与收信人建立连接同样也不能保证信件能到达收信人那里
自寻址套接字工作包括下面三个类DatagramPacket DatagramSocket和 MulticastSocketDatagramPacket对象描绘了自寻址包的地址信息DatagramSocket表示客户程序和服务程序自寻址套接字MulticastSocket描绘了能进行多点传送的自寻址套接字这三个类均位于包内
DatagramPacket类
在使用自寻址包之前你需要首先熟悉DatagramPacket类地址信息和自寻址包以字节数组的方式同时压缩入这个类创建的对象中
DatagramPacket有数个构造函数即使这些构造函数的形式不同但通常情况下他们都有两个共同的参数byte [] buffer 和 int lengthbuffer参数包含了一个对保存自寻址数据包信息的字节数组的引用length表示字节数组的长度
最简单的构造函数是DatagramPacket(byte [] buffer int length)这个构造函数确定了自寻址数据包数组和数组的长度但没有任何自寻址数据包的地址和端口信息这些信息可以后面通过调用方法setAddress(InetAddress addr)和setPort(int port)添加上下面的代码示范了这些函数和方法
byte [] buffer = new byte [];
DatagramPacket dgp = new DatagramPacket (buffer bufferlength);
InetAddress ia = InetAddressgetByName ();
dgpsetAddress (ia);
dgpsetPort (); // Send datagram packet to port
如果你更喜欢在调用构造函数的时候同时包括地址和端口号可以使用DatagramPacket(byte [] buffer int length InetAddress addr int port)函数下面的代码示范了另外一种选择
byte [] buffer = new byte [];
InetAddress ia = InetAddressgetByName ();
DatagramPacket dgp = new DatagramPacket (buffer bufferlength ia
);
有时候在创建了DatagramPacket对象后想改变字节数组和他的长度这时可以通过调用setData(byte [] buffer) 和 setLength(int length)方法来实现在任何时候都可以通过调用getData() 来得到字节数组的引用通过调用getLength()来获得字节数组的长度下面的代码示范了这些方法
byte [] buffer = new byte [];
dgpsetData (buffer);
dgpsetLength (bufferlength);
关于DatagramPacket的更多信息请参考SDK文档
DatagramSocket类
DatagramSocket类在客户端创建自寻址套接字与服务器端进行通信连接并发送和接受自寻址套接字虽然有多个构造函数可供选择但我发现创建客户端自寻址套接字最便利的选择是DatagramSocket()函数而服务器端则是DatagramSocket(int port)函数如果未能创建自寻址套接字或绑定自寻址套接字到本地端口那么这两个函数都将抛出一个SocketException对象一旦程序创建了DatagramSocket对象那么程序分别调用send(DatagramPacket dgp)和 receive(DatagramPacket dgp)来发送和接收自寻址数据包
List显示的DGSClient源代码示范了如何创建自寻址套接字以及如何通过套接字处理发送和接收信息
Listing : DGSClientjava
// DGSClientjava
import javaio*;
import *;
class DGSClient
{
public static void main (String [] args)
{
String host = localhost;
// If user specifies a commandline argument that argument
// represents the host name
if (argslength == )
host = args [];
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 packets message That message originates as a
// String object which gets converted to a sequence of
// bytes when Strings getBytes() method is called The
// conversion uses the platforms 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 = InetAddressgetByName (host);
// Create a DatagramPacket object that encapsulates a
// reference to the byte array and destination address
// information The destination address consists of the
// hosts IP address (as stored in the InetAddress object)
// and port number the port on which the server
// program listens
DatagramPacket dgp = new DatagramPacket (buffer
bufferlength
ia
);
// Send the datagram packet over the socket
ssend (dgp);
// Create a byte array to hold the response from the server
// program
byte [] buffer = new byte [];
// Create a DatagramPacket object that specifies a buffer
// to hold the server programs response the IP address of
// the server programs computer and port number
dgp = new DatagramPacket (buffer
bufferlength
ia
);
// Receive a datagram packet over the socket
sreceive (dgp);
// Print the data returned from the server program and stored
// in the datagram packet
Systemoutprintln (new String (dgpgetData ()));
}
catch (IOException e)
{
Systemoutprintln (etoString ());
}
finally
{
if (s != null)
sclose ();
}
}
}
DGSClient由创建一个绑定任意本地(客户端)端口好的DatagramSocket对象开始然后装入带有文本信息的数组buffer和描述服务器主机IP地址的InetAddress子类对象的引用接下来DGSClient创建了一个DatagramPacket对象该对象加入了带文本信息的缓沖器的引用InetAddress子类对象的引用以及服务端口号 DatagramPacket的自寻址数据包通过方法sent()发送给服务器程序于是一个包含服务程序响应的新的DatagramPacket对象被创建receive()得到响应的自寻址数据包然后自寻址数据包的getData()方法返回该自寻址数据包的一个引用最后关闭DatagramSocket
DGSServer服务程序补充了DGSClient的不足List是DGSServer的源代码
Listing : DGSServerjava
// DGSServerjava
import javaio*;
import *;
class DGSServer
{
public static void main (String [] args) throws IOException
{
Systemoutprintln (Server starting \n);
// Create a datagram socket bound to port Datagram
// packets sent from client programs arrive at this port
DatagramSocket s = new DatagramSocket ();
// Create a byte array to hold data contents of datagram
// packet
byte [] data