?? java語言的socket編程.txt
字號:
StringBuffer buf = new StringBuffer(50);
int c;
String fromServer,usertyped;
while ((fromServer = client_in.readLine()) != null) {
System.out.println("Server: " + fromServer);
while ((c = System.in.read()) != '\n') {
buf.append((char)c);
}
usertyped=buf.toString();
client_out.println(usertyped);
client_out.flush();
buf.setLength(0);
}
} catch (Exception e) {
System.out.println(e);
}
}
}
該程序與前面的程序類似,不同之處在于該程序使用循環:
while ((fromServer = client_in.readLine()) != null) {
...}
反復讀取服務端的輸入,并用:
while ((c = System.in.read()) != '\n') {
buf.append((char)c);
}
usertyped=buf.toString();
client_out.println(usertyped);
語句讀取用戶的鍵盤輸入,發送至服務端。其對話如下所示:
客戶端
C:\xyx\java\sock\bak\ftp>java ftpc
Server: Welcome to the test server
anonymous
Server: 331 Please send Password
xyx@yc.shu.edu.cn
Server: 230 Login OK
bye
服務端
C:\xyx\java\sock\bak\ftp>java ftpserver
got follow infor from client:anonymous
got follow infor from client:xyx@yc.shu.edu.cn
got follow infor from client:bye
值得一提的是,該客戶軟件不僅可以和前面的模擬FTP服務器進行通訊,而且可以和真正的FTP服務器通訊。如將該客戶軟件中IP地址“202.120.127.201”改為某FTP服務器的IP地址:“202.120.127.218”,則可作如下的通訊:
C:\xyx\java\sock\bak\ftp>javac ftpc
Server: 220 sun1000E-1 FTP server (UNIX(r) System V Release 4.0) ready.
USER anonymous
Server: 331 Guest login ok, send ident as password.
PASS xyx@yc.shu.edu.cn
Server: 230 Guest login ok, access restrictions apply.
QUIT
Server: 221 Goodbye.
其中,USER、PASS、QUIT分別為協議規定的用戶帳號、口令及退出的命令。
四、處理客戶端請求
以上的例子均只在服務端與客戶端相互傳送信息,在實用中,服務端應能對客戶端不同的輸入作出不同的響應。本節給出一個服務端處理客戶端請求的例子,協議如下:客戶連接后,服務端發送“Welcome to Time server”信息,客戶端讀取用戶輸入發送給服務端,如果客戶端輸入為Hours,則發送當前小時數至客戶端;如果客戶端輸入為Minutes、Years、Month、Day、Time、Date、down,則分別發送分鐘數、年份、月份、日期、時分秒、年月日至客戶端;客戶端輸入down則結束會話。
其客戶端仍采用上一節編寫的模擬FTP服務器的客戶程序,但需將程序中的端口21改為8885,以便與下面的服務端程序對話。服務端的程序修改如下:
import java.net.*;
import java.io.*;
import java.util.Date;
class server {
public static void main(String args[])
{ try {
ServerSocket server_Socket = new ServerSocket(8885);
Socket client_Socket = server_Socket.accept();
DataInputStream server_in = new DataInputStream(client_Socket.getInputStream());
PrintStream server_out = new PrintStream(client_Socket.getOutputStream());
String inputLine, outputLine;
server_out.println("Welcome to Time server");
server_out.flush();
Date t=new Date();
while ((inputLine = server_in.readLine()) != null) {
System.out.println("got"+inputLine);
String hours = String.valueOf(t.getHours());
String minutes = String.valueOf(t.getMinutes());
String seconds = String.valueOf(t.getSeconds());
String years = String.valueOf(t.getYear());
String month = String.valueOf(t.getMonth());
String day = String.valueOf(t.getDay());
if(inputLine.equalsIgnoreCase("Down"))
break;
else if(inputLine.equalsIgnoreCase("Hours"))
server_out.println("Current Hours is:"+hours);
else if(inputLine.equalsIgnoreCase("Minutes"))
server_out.println("Current Minutes is:"+minutes);
else if(inputLine.equalsIgnoreCase("Years"))
server_out.println("Current Years is:"+years);
else if(inputLine.equalsIgnoreCase("Month"))
server_out.println("Current Month is:"+month);
else if(inputLine.equalsIgnoreCase("Day"))
server_out.println("Current Day is:"+day);
else if(inputLine.equalsIgnoreCase("Time"))
server_out.println("Current Times is:"+hours+":"+minutes+":"+seconds);
else if(inputLine.equalsIgnoreCase("Date"))
server_out.println("Current Date is:"+years+"."+month+"."+day);
else server_out.println("I don't know");
server_out.flush();
}
}
catch(Exception e){
System.out.println(e);
}
}
}
在該程序中,使用類似前面客戶端的方法,用一個循環
while ((inputLine = server_in.readLine()) != null) {
...}
反復讀取客戶端的信息。在循環中根據客戶端傳來的不同信息作不同的處理。
五、程序的優化
為了使程序更優化,可從以下方面入手:
1. 進行出錯處理
如可對每句使用try{...}catch(...){...}的形式處理程序中的例外情況,恰當地返回出錯信息或進行出錯處理等。
2. 關閉打開的Socket和流
結束對話時將所打開的Socket和流都關閉,Java中的SeverScoket、Socket、DataInputStream及DataOutputStream類都提供了方法close()來實現此功能。
3. 支持多次連接
前面的服務端程序在結束一次對話后都將自動結束,如果再有客戶端要建立連接需要重新執行服務端的程序。為了使服務端支持多次連接,只要用一個循環即可。如對前面所有的服務端程序,都可以將執行“accept()”的語句至“}catch(Exception e)”語句的前一行包含在while(true){...}的循環體中而使其支持多次連接。
4. 使用線程
服務端程序一般使用線程,以便在等待客戶端連接時可以處理其他事情。此外,通過為每個客戶端的請求分配一個新的線程,可以使服務端能夠同時支持多個連接,并行處理客戶端的請求。
〖參考資料〗
1. Mary Campione and Kathy Walrath,
"The Java Tutorial",
last updated 4 Mar 96.
ftp://ftp.javasoft.com/docs/tutorial.html.zip
2. Laura Lemay,
Charles L. Perkins,
"Teach Yourself JAVA in 21 Days"
3. "The Java Language Tutorial"
ftp://java.sun.com/docs/progGuide.html.zip
4. elharo@sunsite.unc.edu,
"Brewing Java: A Tutorial",
Last-modified: 1996/9/20,
http://sunsite.unc.edu/javafaq/javatutorial.html
本欄文章均來自于互聯網,版權歸原作者和各發布網站所有,本站收集這些文章僅供學習參考之用。任何人都不能將這些文章用于商業或者其他目的。( ProgramFan.Com )
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -