Java套接字編程(上)(2)
發(fā)表時間:2023-08-20 來源:明輝站整理相關(guān)軟件相關(guān)文章人氣:
[摘要]Socket類 當(dāng)客戶程序需要與服務(wù)器程序通訊的時候,客戶程序在客戶機(jī)創(chuàng)建一個socket對象,Socket類有幾個構(gòu)造函數(shù)。兩個常用的構(gòu)造函數(shù)是 Socket(InetAddress addr,...
Socket類
當(dāng)客戶程序需要與服務(wù)器程序通訊的時候,客戶程序在客戶機(jī)創(chuàng)建一個socket對象,Socket類有幾個構(gòu)造函數(shù)。兩個常用的構(gòu)造函數(shù)是 Socket(InetAddress addr, int port) 和 Socket(String host, int port),兩個構(gòu)造函數(shù)都創(chuàng)建了一個基于Socket的連接服務(wù)器端流套接字的流套接字。對于第一個InetAddress子類對象通過addr參數(shù)獲得服務(wù)器主機(jī)的IP地址,對于第二個函數(shù)host參數(shù)包被分配到InetAddress對象中,如果沒有IP地址與host參數(shù)相一致,那么將拋出UnknownHostException異常對象。兩個函數(shù)都通過參數(shù)port獲得服務(wù)器的端口號。假設(shè)已經(jīng)建立連接了,網(wǎng)絡(luò)API將在客戶端基于Socket的流套接字中捆綁客戶程序的IP地址和任意一個端口號,否則兩個函數(shù)都會拋出一個IOException對象。
如果創(chuàng)建了一個Socket對象,那么它可能通過調(diào)用Socket的 getInputStream()方法從服務(wù)程序獲得輸入流讀傳送來的信息,也可能通過調(diào)用Socket的 getOutputStream()方法獲得輸出流來發(fā)送消息。在讀寫活動完成之后,客戶程序調(diào)用close()方法關(guān)閉流和流套接字,下面的代碼創(chuàng)建了一個服務(wù)程序主機(jī)地址為198.163.227.6,端口號為13的Socket對象,然后從這個新創(chuàng)建的Socket對象中讀取輸入流,然后再關(guān)閉流和Socket對象。
Socket s = new Socket ("198.163.227.6", 13);
InputStream is = s.getInputStream ();
// Read from the stream.
is.close ();
s.close ();
接下面我們將示范一個流套接字的客戶程序,這個程序?qū)?chuàng)建一個Socket對象,Socket將訪問運(yùn)行在指定主機(jī)端口10000上的服務(wù)程序,如果訪問成功客戶程序?qū)⒔o服務(wù)程序發(fā)送一系列命令并打印服務(wù)程序的響應(yīng)。List2使我們創(chuàng)建的程序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)
{
}
}
}
}
運(yùn)行這段程序?qū)玫较旅娴慕Y(jié)果:
Tue Jan 29 18:11:51 CST 2002
TUESDAY
29
29
SSClient創(chuàng)建了一個Socket對象與運(yùn)行在主機(jī)端口10000的服務(wù)程序聯(lián)系,主機(jī)的IP地址由host變量確定。SSClient將獲得Socket的輸入輸出流,圍繞BufferedReader的輸入流和PrintWriter的輸出流對字符串進(jìn)行讀寫操作就變得非常容易,SSClient個服務(wù)程序發(fā)出各種date/time命令并得到響應(yīng),每個響應(yīng)均被打印,一旦最后一個響應(yīng)被打印,將執(zhí)行Try/Catch/Finally結(jié)構(gòu)的Finally子串,F(xiàn)inally子串將在關(guān)閉Socket之前關(guān)閉BufferedReader 和 PrintWriter。
在SSClient源代碼編譯完成后,可以輸入java SSClient 來執(zhí)行這段程序,如果有合適的程序運(yùn)行在不同的主機(jī)上,采用主機(jī)名/IP地址為參數(shù)的輸入方式,比如www.sina.com.cn是運(yùn)行服務(wù)器程序的主機(jī),那么輸入方式就是java SSClient www.sina.com.cn。
技巧
Socket類包含了許多有用的方法。比如getLocalAddress()將返回一個包含客戶程序IP地址的InetAddress子類對象的引用;getLocalPort()將返回客戶程序的端口號;getInetAddress()將返回一個包含服務(wù)器IP地址的InetAddress子類對象的引用;getPort()將返回服務(wù)程序的端口號。