import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; //每个线程去独自完成他们的客户端请求 public class MyServer { private static ExecutorService executorService = Executors.newCachedThreadPool(); private static class HandleMsg implements Runnable{ Socket client; public HandleMsg(Socket client){ this.client = client; } @Override public void run() { BufferedReader bufferedReader = null; PrintWriter printWriter = null; try { bufferedReader = new BufferedReader(new InputStreamReader(client.getInputStream())); printWriter = new PrintWriter(client.getOutputStream(),true); //true是随时刷新 String inputLine = null; long a = System.currentTimeMillis(); while ((inputLine = bufferedReader.readLine())!=null){// 卡住,等待客户输入,一直等待,直到客户端printWriter输出流关闭, printWriter.println(inputLine+"server:"); } long b = System.currentTimeMillis(); System.out.println("此线程花费了:"+(b-a)+"秒!"); } catch (IOException e) { e.printStackTrace(); }finally { try { bufferedReader.close(); printWriter.close(); client.close(); } catch (IOException e) { e.printStackTrace(); } } } } public static void main(String[] args) throws IOException { ServerSocket server = new ServerSocket(8686); Socket client = null; while (true){ client = server.accept(); //服务端监听到一个客户端请求,卡住,等待连接, System.out.println(client.getRemoteSocketAddress()+"地址的客户端连接成功!"); executorService.submit(new HandleMsg(client)); } } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.InetSocketAddress; import java.net.Socket; public class MyClient { public static void main(String[] args) throws IOException { Socket client = null; PrintWriter printWriter = null; BufferedReader bufferedReader = null; try { client = new Socket(); client.connect(new InetSocketAddress("localhost",8686)); printWriter = new PrintWriter(client.getOutputStream(),true); printWriter.println("hello"); printWriter.flush(); bufferedReader = new BufferedReader(new InputStreamReader(client.getInputStream())); //读取服务器返回的信息并进行输出 System.out.println("来自服务器的信息是:"+bufferedReader.readLine()); } catch (IOException e) { e.printStackTrace(); }finally { printWriter.close(); bufferedReader.close(); client.close(); } } }