當客戶程序需要與服務器程序通訊的時候,客戶程序在客戶機創建一個socket對象,Socket類有幾個構造函數。兩個常用的構造函數是 Socket(InetAddress addr, int port) 和 Socket(String host, int port),兩個構造函數都創建了一個基於Socket的連接服務器端流套接字的流套接字。對於第一個InetAddress子類對象通過addr參數獲得服務器主機的IP地址,對於第二個函數host參數包被分配到InetAddress對象中,如果沒有IP地址與host參數相一致,那麼將拋出UnknownHostException異常對象。兩個函數都通過參數port獲得服務器的端口號。假設已經建立連接了,網絡API將在客戶端基於Socket的流套接字中捆綁客戶程序的IP地址和任意一個端口號,否則兩個函數都會拋出一個IOException對象。
如果創建了一個Socket對象,那麼它可能通過調用Socket的 getInputStream()方法從服務程序獲得輸入流讀傳送來的信息,也可能通過調用Socket的 getOutputStream()方法獲得輸出流來發送消息。在讀寫活動完成之後,客戶程序調用close()方法關閉流和流套接字,下面的代碼創建了一個服務程序主機地址為198.163.227.6,端口號為13的Socket對象,然後從這個新創建的Socket對象中讀取輸入流,然後再關閉流和Socket對象。
Socket s = new Socket ("198.163.227.6", 13);
InputStream is = s.getInputStream ();
// Read from the stream.
is.close ();
s.close ();
接下面我們將示范一個流套接字的客戶程序,這個程序將創建一個Socket對象,Socket將訪問運行在指定主機端口10000上的服務程序,如果訪問成功客戶程序將給服務程序發送一系列命令並打印服務程序的響應。List2使我們創建的程序SSClient的源代碼:
Listing 2: SSClient.java
// SSClient.java
import java.io.*;
import java.net.*;
class SSClient
{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];
BufferedReader br = null;
PrintWriter pw = null;
Socket s = null;
try
{// Create a socket that attempts to connect to the server
// program on the host at port 10000.
s = new Socket (host, 10000);
// Create an input stream reader that chains to the socket′s
// byte-oriented input stream. The input stream reader
// converts bytes read from the socket to characters. The
// conversion is based on the platform′s default character
// set.
InputStreamReader isr;
isr = new InputStreamReader (s.getInputStream ());
// Create a buffered reader that chains to the input stream
// reader. The buffered reader supplies a convenient method
// for reading entire lines of text.
br = new BufferedReader (isr);
// Create a print writer that chains to the socket′s byte-
// oriented output stream. The print writer creates an
// intermediate output stream writer that converts
// characters sent to the socket to bytes. The conversion
// is based on the platform′s default character set.
pw = new PrintWriter (s.getOutputStream (), true);
// Send the DATE command to the server.
pw.println ("DATE");
// Obtain and print the current date/time.
System.out.println (br.readLine ());
// Send the PAUSE command to the server. This allows several
// clients to start and verifies that the server is spawning
// multiple threads.
pw.println ("PAUSE");
// Send the DOW command to the server.
pw.println ("DOW");
// Obtain and print the current day of week.
System.out.println (br.readLine ());
// Send the DOM command to the server.
pw.println ("DOM");
// Obtain and print the current day of month.
System.out.println (br.readLine ());
// Send the DOY command to the server.
pw.println ("DOY");
// Obtain and print the current day of year.
System.out.println (br.readLine ());
}
catch (IOException e)
{System.out.println (e.toString ());
}
finally
{try
{ if (br != null)
br.close ();
if (pw != null)
pw.close ();
if (s != null)
s.close ();
}
catch (IOException e)
{
}
} }}
運行這段程序將會得到下面的結果:
Tue Jan 29 18:11:51 CST 2002
TUESDAY
29
29
SSClient創建了一個Socket對象與運行在主機端口10000的服務程序聯系,主機的IP地址由host變量確定。SSClient將獲得Socket的輸入輸出流,圍繞BufferedReader的輸入流和PrintWriter的輸出流對字符串進行讀寫操作就變得非常容易,SSClient個服務程序發出各種date/time命令並得到響應,每個響應均被打印,一旦最後一個響應被打印,將執行Try/Catch/Finally結構的Finally子串,Finally子串將在關閉Socket之前關閉BufferedReader 和 PrintWriter。
在SSClient源代碼編譯完成後,可以輸入java SSClient 來執行這段程序,如果有合適的程序運行在不同的主機上,采用主機名/IP地址為參數的輸入方式,比如www.sina.com.cn是運行服務器程序的主機,那麼輸入方式就是java SSClient www.sina.com.cn。
技巧
Socket類包含了許多有用的方法。比如getLocalAddress()將返回一個包含客戶程序IP地址的InetAddress子類對象的引用;getLocalPort()將返回客戶程序的端口號;getInetAddress()將返回一個包含服務器IP地址的InetAddress子類對象的引用;getPort()將返回服務程序的端口號。