第10章 网络编程 04_TCP_Socket_4

来源:互联网 发布:linux wget命令不存在 编辑:程序博客网 时间:2024/06/05 07:06

鱼欲遇雨:每日都学习一点,持之以恒,天道酬勤!不能用电脑时,提前补上!(2012.9.5)


同步聊天对话!

// TaleServer.javaimport java.net.*;import java.io.*;public class TalkServer {public static void main(String args[]) {try{ServerSocket server = null;try{server = new ServerSocket(4700);}catch (Exception e){System.out.println("can not listen to : " + e);}Socket socket = null;try{socket = server.accept();}catch (Exception e){System.out.println("Error: " + e);}String line;BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));PrintWriter os = new PrintWriter(socket.getOutputStream());BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));System.out.println("Client: " + is.readLine());line = sin.readLine();while(! line.equals("bey")){os.println(line);os.flush();System.out.println("Server: " + line);System.out.println("Client: " + is.readLine());line = sin.readLine();}is.close();os.close();sin.close();socket.close();server.close();}catch (Exception e){System.out.println("Error: " + e);}}}

// TalkClient.javaimport java.net.*;import java.io.*;public class TalkClient {public static void main(String args[]) {try{Socket socket = new Socket("127.0.0.1", 4700);BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));PrintWriter os = new PrintWriter(socket.getOutputStream());BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));String readline;readline = sin.readLine();while(!readline.equals("bey")) {os.println(readline);os.flush();System.out.println("Client: " + readline);System.out.println("Server: " + is.readLine());readline = sin.readLine();}os.close();is.close();socket.close();}catch (Exception e){System.out.println("Error: " + e);}}}