public class TalkServer{
public static void main(String args[]) {
try{
ServerSocket server=null;
try{
server=new ServerSocket(4700);
//創(chuàng)建一個ServerSocket在端口4700監(jiān)聽客戶請求
}catch(Exception e) {
System.out.println("can not listen to:"+e);
//出錯,打印出錯信息
}
Socket socket=null;
try{
socket=server.accept();
//使用accept()阻塞等待客戶請求,有客戶
//請求到來則產(chǎn)生一個Socket對象,并繼續(xù)執(zhí)行
}catch(Exception e) {
System.out.println("Error."+e);
//出錯,打印出錯信息
}
String line;
BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream()));
//由Socket對象得到輸入流,并構(gòu)造相應(yīng)的BufferedReader對象
PrintWriter os=newPrintWriter(socket.getOutputStream());
//由Socket對象得到輸出流,并構(gòu)造PrintWriter對象
BufferedReader sin=new BufferedReader(new InputStreamReader(System.in));
//由系統(tǒng)標(biāo)準(zhǔn)輸入設(shè)備構(gòu)造BufferedReader對象
System.out.println("Client:"+is.readLine());
//在標(biāo)準(zhǔn)輸出上打印從客戶端讀入的字符串
line=sin.readLine();
//從標(biāo)準(zhǔn)輸入讀入一字符串
while(!line.equals("bye")){
//如果該字符串為 "bye",則停止循環(huán)
os.println(line);
//向客戶端輸出該字符串
os.flush();
//刷新輸出流,使Client馬上收到該字符串
System.out.println("Server:"+line);
//在系統(tǒng)標(biāo)準(zhǔn)輸出上打印讀入的字符串
System.out.println("Client:"+is.readLine());
//從Client讀入一字符串,并打印到標(biāo)準(zhǔn)輸出上
line=sin.readLine();
//從系統(tǒng)標(biāo)準(zhǔn)輸入讀入一字符串
} //繼續(xù)循環(huán)
os.close(); //關(guān)閉Socket輸出流
is.close(); //關(guān)閉Socket輸入流
socket.close(); //關(guān)閉Socket
server.close(); //關(guān)閉ServerSocket
}catch(Exception e){
System.out.println("Error:"+e);
//出錯,打印出錯信息
}
}
}