标签:客户 stack 处理 rgs 传统 and 创建 block 适用于
实例说明
实例代码:
public class BIOServer {
    public static void main(String[] args) throws Exception {
        //1、创建一个线程池
        ExecutorService threadPool = Executors.newCachedThreadPool();
        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("服务器启动了!!!");
        while (true){
            //监听,等待客户端连接
            final Socket socket = serverSocket.accept();
            System.out.println("连接到一个客户端");
            //2、如果有客户端连接了,就创建一个线程,与之通讯(单独写一个方法)
            threadPool.execute(new Runnable() {
                public void run() {
                    //与客户端进行通讯
                    handler(socket);
                }
            });
        }
    }
    //编写一个与客户端通讯的handler方法
    public static void handler(Socket socket){
        //用于接收数据
        byte[] bytes = new byte[1024];
        //通过socket获取输入流
        InputStream inputStream = null;
        try {
            System.out.println("线程id="+Thread.currentThread().getId()+"名字="+Thread.currentThread().getName());
            inputStream = socket.getInputStream();
            //循环读取客户端发送的数据
            while(true){
                int read = inputStream.read(bytes);
                if (read!=-1){
                    //输出客户端发送的数据
                    System.out.println(“收到信息:”+new String(bytes,0,read));
                }else{
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            System.out.println("关闭与客户端的连接......");
            try {
                inputStream.close();
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}测试结果:
服务器启动了!!!
连接到一个客户端
线程id=12名字=pool-1-thread-1
收到消息:nihao标签:客户 stack 处理 rgs 传统 and 创建 block 适用于
原文地址:https://www.cnblogs.com/lee0527/p/11954319.html