1 package 线程安全的讨论; 2 import java.io.BufferedReader; 3 import java.io.IOException; 4 import java.io.InputStreamReader; 5 import java.io.PrintStream; 6 import java.net.ServerSocket; 7 import java.net.Socket; 8 9 public class Server { 10 public static void main(String[] args) throws IOException { 11 //创建月hi个ServerSocket,用于监听客户端Socket的连接请求 12 ServerSocket ss=new ServerSocket(3000); 13 System.out.println("服务器启动了"); 14 while(true) 15 { 16 17 Socket s=ss.accept(); 18 //输出流,输出到客户端 19 PrintStream p=new PrintStream(s.getOutputStream()); 20 //输入流 21 BufferedReader buf=new BufferedReader(new InputStreamReader(s.getInputStream())); 22 23 24 //读取服务器端的信息,并echo到客户端,以bye结束 25 System.out.println("accept"+s.getInetAddress()); 26 27 28 while(true) 29 { 30 String line=buf.readLine(); 31 if(line.equals("bye")) 32 { 33 System.out.println("good bye"); 34 break; 35 } 36 else 37 { 38 System.out.println(line); 39 } 40 41 42 } 43 } 44 45 46 } 47 48 }
2.客户端
package 线程安全的讨论; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.net.Socket; import java.util.Scanner; public class Client { public static void main(String[] args) { try { Socket socket=new Socket("127.0.0.1",3000); //将socket对应的输入流包装成BufferedReader BufferedReader br=new BufferedReader( new InputStreamReader(System.in)); PrintStream pt=new PrintStream(socket.getOutputStream()); String line=null; while((line=br.readLine()) != null) { pt.println(line); } br.close(); socket.close(); } catch(IOException e) { e.printStackTrace(); } } }
时间: 2024-11-08 01:24:36