Netty学习-01

xiaoxiao2021-02-28  105

传统IO

Demo1:

package com.study.netty.test; import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; public class IoServerTest { public static void main(String[] args) throws Exception { // 创建socket服务,监听8081端口 ServerSocket server = new ServerSocket(8081); System.out.println("......服务器启动!"); while (true) { // 获取一个套接字(阻塞) final Socket socket = server.accept(); System.out.println("--->来个一个新客户端!"+System.currentTimeMillis()); handler(socket); } } /** * 读取数据 * * @param socket * @throws Exception */ public static void handler(Socket socket) { try { byte[] bytes = new byte[1024]; InputStream inputStream = socket.getInputStream(); while (true) { // 读取数据(阻塞) int read = inputStream.read(bytes); System.out.println("--->读取数据!"+System.currentTimeMillis()); if (read != -1) { System.out.println(new String(bytes, 0, read)); } else { break; } } } catch (Exception e) { e.printStackTrace(); } finally { try { System.out.println("socket关闭"); socket.close(); } catch (IOException e) { e.printStackTrace(); } } } } 服务启动,此处阻塞等待客户端

用telnet模拟客户端:

此时阻塞在读取数据

此图表明阻塞点为读取数据:

下图表明:两个客户端连接的时候会只会为其中一个客户服务,另外一个客户端处于阻塞状态

总结:单线程情况下只能有一个客户端 Demon2: package com.study.netty.test; 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 IoServerOneTest { public static void main(String[] args) throws Exception { ExecutorService newCachedThreadPool = Executors.newCachedThreadPool(); // 创建socket服务,监听8081端口 ServerSocket server = new ServerSocket(8081); System.out.println("......服务器启动!"); while (true) { // 获取一个套接字(阻塞) final Socket socket = server.accept(); System.out.println("--->来个一个新客户端!"+System.currentTimeMillis()); newCachedThreadPool.execute(new Runnable() { public void run() { // 业务处理 handler(socket); } }); } } /** * 读取数据 * * @param socket * @throws Exception */ public static void handler(Socket socket) { try { byte[] bytes = new byte[1024]; InputStream inputStream = socket.getInputStream(); while (true) { // 读取数据(阻塞) int read = inputStream.read(bytes); System.out.println("--->读取数据!"+System.currentTimeMillis()); if (read != -1) { System.out.println(new String(bytes, 0, read)); } else { break; } } } catch (Exception e) { e.printStackTrace(); } finally { try { System.out.println("socket关闭"); socket.close(); } catch (IOException e) { e.printStackTrace(); } } } } 下图表明多客户端在有线程池时不会阻塞: 总结:用线程池可以有多个客户端连接,但是非常消耗性能
转载请注明原文地址: https://www.6miu.com/read-62039.html

最新回复(0)