作业的目标
目标1:Socket简单应用。 把教材P238-230中例11-5代码输入到我们的代码编辑器,调试并运行(80分)。
P238客户端程序
import java.io.*; import java.net.*; public class ChatClient { public static void main(String args[]){ try{ Socket socket=new Socket("127.0.0.1",4001); System.out.println("输入你要说的话,如果要退出输入bye"); 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("bye")){ 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); } } }
P238-230 服务器端程序
import java.io.*; import java.net.*; import java.applet.Applet; public class ChatServer { public static void main(String args[]){ try{ ServerSocket server=null; try{ server=new ServerSocket(4001); System.out.println("准备好了,退出输入bye"); }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("bye")){ os.print(line); os.flush(); System.out.println("Client:"+is.readLine()); line=sin.readLine(); } os.close(); is.close(); socket.close(); server.close(); }catch(Exception e){ System.out.println("Error:"+e); } } }
时间: 2024-10-11 08:58:27