package test; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.net.ServerSocket; import java.net.Socket; class ThreadSocket implements Runnable{ private Socket client = null ; public ThreadSocket(Socket client){ this.client = client ; } public void run(){ BufferedReader buf = null ; // 接收输入流 PrintStream out = null ; // 打印流输出最方便 try{ out = new PrintStream(client.getOutputStream()) ; // 准备接收客户端的输入信息 buf = new BufferedReader(new InputStreamReader(client.getInputStream())) ; boolean flag = true ; // 标志位。表示能够一直接收并回应信息 while(flag){ String str = buf.readLine() ; // 接收客户端发送的内容 if(str==null||"".equals(str)){ // 表示没有内容 flag = false ; // 退出循环 }else{ if("bye".equals(str)){ // 假设输入的内容为bye表示结束 flag = false ; }else{ out.println("ECHO : " + str) ; // 回应信息 } } } client.close() ; }catch(Exception e){} } } public class Test { public static void main(String[] args) throws IOException { server3(); } public static void server3() throws IOException{ ServerSocket server=new ServerSocket(8888); while(true){ Socket client=server.accept(); new Thread(new ThreadSocket(client)).start(); } } public static void server2() throws IOException{ ServerSocket server=new ServerSocket(8888); Socket client=server.accept(); boolean flag=true; while(flag){ BufferedReader in=new BufferedReader(new InputStreamReader(client.getInputStream())); PrintStream print=new PrintStream(client.getOutputStream()); boolean f=true; while(f){ String str=in.readLine(); if(str==null||"".equals(str)){ f=false; }else{ if("bye".equals(str)){ f=false; }else{ print.println("Echo::"+str); } } print.print(str); } print.close(); } client.close(); server.close(); } public static void server1() throws IOException{ ServerSocket server=new ServerSocket(8888); Socket client=server.accept(); PrintStream print=new PrintStream(client.getOutputStream()); String str="Hello world"; print.print(str); print.close(); client.close(); server.close(); } /** *baidu的IP地址:119.75.217.109 */ }
package test; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.net.Socket; public class Socket01{ public static void main(String args[]) throws IOException{ Socket socket=new Socket("localhost",8888); BufferedReader buf=new BufferedReader(new InputStreamReader(socket.getInputStream())); BufferedReader input=new BufferedReader(new InputStreamReader(System.in)); PrintStream out=new PrintStream(socket.getOutputStream()); boolean flag = true ; // 定义标志位 while(flag){ System.out.print("输入信息:") ; String str = input.readLine() ; // 接收键盘的输入信息 out.println(str) ; if("bye".equals(str)){ flag = false ; }else{ String echo = buf.readLine() ; // 接收返回结果 System.out.println(echo) ; // 输出回应信息 } } buf.close(); out.close(); input.close(); socket.close(); } }; /** read1(): hello read2(): hello hello **/