在服务器端为每个客户端配置两个线程是必须的,一个用来接收请求,一个用来发送请求,用户每一次请求后就和这两个线程进行绑定,然后再在线程里对客户进行业务操作,服务器端则在主线程中继续拿取下一个请求,再分配两个线程,再进行客户端绑定。换句话说,异步处理不是只一种socket处理的方式,它是socket会话处理中最好的方式。
总结一下,java对socket的处理机制要求我们必须使用两个方法来处理socket连接
1.使用死循环来循环获取socket连接,两个好处:可以不断获取新的连接并且可以防止服务器代码运行到尾部down掉
2.使用多线程来处理当前客户端请求的业务,服务器很忙,没空一步一步的跟你把代码执行下去,所以每一个客户端都需要绑定一个输出线程和一个输入线程对它的业务进行处理
服务器端:
package 异步socket; import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.util.Scanner; /** * Created by z84102272 on 2018/8/9. */ public class Server { public static void main(String[] args){ ServerSocket ss = null; try { ss = new ServerSocket(8888); System.out.println("启动服务器!"); }catch (IOException e){ e.printStackTrace(); } while (true){ try{ Socket s = ss.accept(); System.out.println("客户端" + s.getInetAddress().getLocalHost() + "已连接到服务器"); BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream())); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); bw.write("你已和服务器建立通信,现在进入你的请求处理线程" + " "); bw.flush(); Scanner sc = new Scanner(System.in); Thread readThread = new Thread(){ public void run(){ while (true){ try { String msg = br.readLine(); System.out.println(msg); }catch (IOException e){ e.printStackTrace(); } } } }; Thread writeThread = new Thread(){ public void run(){ while (true){ try{ bw.write(sc.next() + " "); bw.flush(); }catch (IOException e){ e.printStackTrace(); } } } }; readThread.start(); writeThread.start(); }catch (IOException e){ e.printStackTrace(); } } } }
客户端:
package 异步socket; import java.io.*; import java.net.Socket; import java.net.UnknownHostException; import java.util.Scanner; /** * Created by z84102272 on 2018/8/9. */ public class Client { public static void main(String[] args){ try{ Socket s = new Socket("127.0.0.1",8888); //构建IO InputStream is = s.getInputStream(); OutputStream os = s.getOutputStream(); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os)); BufferedReader br = new BufferedReader(new InputStreamReader(is)); Scanner sc = new Scanner(System.in); Thread readThread = new Thread(){ public void run(){ while (true){ String msg = null; try { msg = br.readLine(); }catch (IOException e){ e.printStackTrace(); } System.out.println(msg); } } }; Thread writeThread = new Thread(){ public void run(){ while (true){ try{ bw.write(sc.next() + " "); bw.flush(); }catch (IOException e){ e.printStackTrace(); } } } }; readThread.start(); writeThread.start(); }catch (UnknownHostException e){ e.printStackTrace(); }catch (IOException e){ e.printStackTrace(); } } }