自尋址套接字(Datagram Sockets)
因為使用流套接字的每個連接均要花費一定的時間
與TCP保證信息到達信息目的地的方式不同
自尋址套接字工作包括下面三個類
DatagramPacket類
在使用自尋址包之前
DatagramPacket有數個構造函數
最簡單的構造函數是DatagramPacket(byte [] buffer
byte [] buffer = new byte [
DatagramPacket dgp = new DatagramPacket (buffer
InetAddress ia = InetAddress
dgp
dgp
如果你更喜歡在調用構造函數的時候同時包括地址和端口號
byte [] buffer = new byte [
InetAddress ia = InetAddress
DatagramPacket dgp = new DatagramPacket (buffer
有時候在創建了DatagramPacket對象後想改變字節數組和他的長度
byte [] buffer
dgp
dgp
關於DatagramPacket的更多信息請參考SDK文檔
DatagramSocket類
DatagramSocket類在客戶端創建自尋址套接字與服務器端進行通信連接
List
Listing
// DGSClient
import java
import
class DGSClient
{
public static void main (String [] args)
{
String host =
// If user specifies a command
// represents the host name
if (args
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 packet
// String object
// bytes when String
// conversion uses the platform
byte [] buffer;
buffer = new String (
// 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
// Create a DatagramPacket object that encapsulates a
// reference to the byte array and destination address
// information
// host
// and port number
// program listens
DatagramPacket dgp = new DatagramPacket (buffer
buffer
ia
// Send the datagram packet over the socket
s
// Create a byte array to hold the response from the server
// program
byte [] buffer
// Create a DatagramPacket object that specifies a buffer
// to hold the server program
// the server program
dgp = new DatagramPacket (buffer
buffer
ia
// Receive a datagram packet over the socket
s
// Print the data returned from the server program and stored
// in the datagram packet
System
}
catch (IOException e)
{
System
}
finally
{
if (s != null)
s
}
}
}
DGSClient由創建一個綁定任意本地(客戶端)端口好的DatagramSocket對象開始
DGSServer服務程序補充了DGSClient的不足
Listing
// DGSServer
import java
import
class DGSServer
{
public static void main (String [] args) throws IOException
{
System
// Create a datagram socket bound to port
// 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
From:http://tw.wingwit.com/Article/program/Java/JSP/201311/19527.html