【从BIO到Netty】1.BIO存在的问题
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端代码
这段代码存在的性能问题:
- 红色部分,线程会被阻塞
- 每个连接,都分配给一个单独的线程进行处理
相关推荐
fengshantao 2020-10-29
arctan0 2020-10-14
爱传文档 2020-07-28
gzx0 2020-07-05
fengshantao 2020-07-04
fengshantao 2020-07-02
arctan0 2020-06-19
arctan0 2020-06-16
gzx0 2020-06-14
fengshantao 2020-06-13
gzx0 2020-06-12
arctan0 2020-06-11
fengshantao 2020-06-11
mbcsdn 2020-05-19
arctan0 2020-05-16
爱传文档 2020-05-08