當客戶程序需要與服務器程序通訊的時候,客戶程序在客戶機創(chuàng)建一個socket對象,Socket類有幾個構造函數(shù)。兩個常用的構造函數(shù)是 Socket(InetAddress addr, int port) 和 Socket(String host, int port),兩個構造函數(shù)都創(chuàng)建了一個基于Socket的連接服務器端流套接字的流套接字。對于第一個InetAddress子類對象通過addr參數(shù)獲得服務器主機的ip地址,對于第二個函數(shù)host參數(shù)包被分配到InetAddress對象中,假如沒有IP地址與host參數(shù)相一致,那么將拋出UnknownHostException異常對象。兩個函數(shù)都通過參數(shù)port獲得服務器的端口號。假設已經(jīng)建立連接了,網(wǎng)絡API將在客戶端基于Socket的流套接字中捆綁客戶程序的IP地址和任意一個端口號,否則兩個函數(shù)都會拋出一個IOException對象。
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.