Java BIO 应用实例
1. 实例说明:
1) 使用 BIO 模型编写一个服务器端,监听 6666 端口,当有客户端连接时,就启动一个线程与之通讯。
2) 要求使用线程池机制改善,可以连接多个客户端.
3) 服务器端可以接收客户端发送的数据(telnet 方式即可)。
4) 代码演示
package com.example.netty.bio; 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; /** * 线程池机制: * 思路: * 1.创建一个线程池; * 2.有客户端连接就创建一个线程,与之通讯(单独写一个方法) */ public class BIOServer { public static void main(String[] args) throws IOException { ExecutorService newCachedThreadPool = Executors.newCachedThreadPool(); final ServerSocket serverSocket = new ServerSocket(6666); System.out.println("服务器启动了,线程ID:" + Thread.currentThread().getId() + " 线程名称:" + Thread.currentThread().getName()); while (true) { System.out.println("线程:" + Thread.currentThread().getName() + "等待连接..."); Socket socket = serverSocket.accept(); System.out.println("连接到客户端,线程ID:" + Thread.currentThread().getId() + " 线程名称:" + Thread.currentThread().getName()); newCachedThreadPool.execute(() -> { handle(socket); }); } } //编写一个handle与客户端通讯 private static void handle(Socket socket) { try { byte[] bytes = new byte[1024]; InputStream inputStream = socket.getInputStream(); while (true) { System.out.println("线程:" + Thread.currentThread().getName() + "等待read..."); int read = inputStream.read(bytes); if (read != -1) { System.out.println("读取到数据,线程ID:" + Thread.currentThread().getId() + " 线程名称:" + Thread.currentThread().getName()); System.out.println("客户端发送的数据:" + new String(bytes, 0, read)); } else { break; } } } catch (Exception e) { e.printStackTrace(); } finally { try { System.out.println("关闭与client的连接"); socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }
原文:https://www.cnblogs.com/luliang888/p/12401268.html