package org.scaventz.bio; import io.netty.util.CharsetUtil; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.*; public class BioEchoServer { private ServerSocket serverSocket; private final int PORT = 8080; private ExecutorService exec = new ThreadPoolExecutor(10, 20, 5, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(50)); public void init() throws IOException { serverSocket = new ServerSocket(); serverSocket.bind(new InetSocketAddress(PORT)); } public void startup() throws IOException { while (true) { System.out.println("等待连接"); Socket socket = serverSocket.accept(); System.out.println("与 " + socket.getInetAddress() + " 建立连接"); exec.execute(new Thread(() -> { InputStream inputStream = null; OutputStream outputStream = null; try { inputStream = socket.getInputStream(); outputStream = socket.getOutputStream(); TimeUnit.SECONDS.sleep(2); byte[] bytes = new byte[inputStream.available()]; inputStream.read(bytes); System.out.println("[客户端-" + socket.getRemoteSocketAddress() + "]: " + new String(bytes, CharsetUtil.UTF_8)); outputStream.write(bytes); } catch (InterruptedException | IOException e) { e.printStackTrace(); } finally { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } })); } } public static void main(String[] args) throws IOException { BioEchoServer server = new BioEchoServer(); server.init(); server.startup(); } }
上面是一段BIO模式的Server端代码
这段代码存在的性能问题:
- 红色部分,线程会被阻塞
- 每个连接,都分配给一个单独的线程进行处理