Java中的网络编程,指的就是Socket
传统IO服务写法:
【客户端】
package com.zy.socket; import java.io.IOException; import java.net.Socket; import java.util.Date; public class SocketClient { public static void main(String[] args) { new Thread(() -> { try { Socket socket = new Socket("127.0.0.1", 9231); while (true) { try { socket.getOutputStream().write((new Date() + ": hello world").getBytes()); socket.getOutputStream().flush(); Thread.sleep(2000); } catch (Exception e) { } } } catch (IOException e) { } }).start(); } }
【服务端】
package com.zy.socket; import java.io.IOException; import java.net.Socket; import java.util.Date; public class SocketClient { public static void main(String[] args) { new Thread(() -> { try { Socket socket = new Socket("127.0.0.1", 9231); while (true) { try { socket.getOutputStream().write((new Date() + ": hello world").getBytes()); socket.getOutputStream().flush(); Thread.sleep(2000); } catch (Exception e) { } } } catch (IOException e) { } }).start(); } }
但是上面的写法存在问题,即没来一个新的socket连接,系统就必须开启一个新的线程去处理,久而久之,当高并发时,系统会吃不消
下面是才用线程池的改良版
【服务端】
package com.zy.socket; import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class SocketServerPool { public static void main(String[] args) throws Exception { ServerSocket serverSocket = new ServerSocket(9231); ExecutorService pool = Executors.newFixedThreadPool(5); new Thread(() -> { while(true) { try { // accept是阻塞的,只有当当前socket接收到信息时,才会往下执行 Socket socket = serverSocket.accept(); pool.submit(new MySocketTask(socket)); } catch (Exception e) { // TODO: handle exception } } }).start(); } } class MySocketTask implements Runnable { private Socket socket; public MySocketTask(Socket socket) { this.socket = socket; } @Override public void run() { System.out.println("正在执行socket:"+Thread.currentThread().getName()); try { byte[] data = new byte[1024]; InputStream inputStream = socket.getInputStream(); while(true) { int len; while((len = inputStream.read(data)) != -1) { System.out.println(new String(data, 0, len)); } } } catch (Exception e) { // TODO: handle exception } System.out.println("socket 执行完毕"); } }