设为首页 加入收藏

TOP

Reactor模式(三)
2019-09-17 15:06:49 】 浏览:37
Tags:Reactor 模式
(requestBuffer.position() == 0) return; // 如果没数据了, 则不继续后面的处理 requestBuffer.flip(); byte[] content = new byte[requestBuffer.limit()]; requestBuffer.get(content); System.out.println(new String(content)); System.out.println( Thread.currentThread().getName() + "收到数据,来自:" + ch.getRemoteAddress()); // TODO 业务操作 数据库、接口... workPool.submit(() -> {}); // 响应结果 200 String response = "HTTP/1.1 200 OK\r\n" + "Content-Length: 11\r\n\r\n" + "Hello World"; ByteBuffer buffer = ByteBuffer.wrap(response.getBytes()); while (buffer.hasRemaining()) { ch.write(buffer); } } }; } } // 始化channel,并且绑定一个eventLoop线程 private void initAndRegister() throws Exception { // 1、 创建ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.configureBlocking(false); // 2、 将serverSocketChannel注册到selector int index = new Random().nextInt(mainReactorThreads.length); mainReactorThreads[index].doStart(); SelectionKey selectionKey = mainReactorThreads[index].register(serverSocketChannel); selectionKey.interestOps(SelectionKey.OP_ACCEPT); } // 绑定端口 private void bind() throws IOException { // 1、 正式绑定端口,对外服务 serverSocketChannel.bind(new InetSocketAddress(8080)); System.out.println("启动完成,端口8080"); } public static void main(String[] args) throws Exception { NIOReactor nioReactor = new NIOReactor(); // 1、 创建main和sub两组线程 nioReactor.newGroup(); // 2、 创建serverSocketChannel,注册到mainReactor线程上的selector上 nioReactor.initAndRegister(); // 3、 为serverSocketChannel绑定端口 nioReactor.bind(); } }

?
首页 上一页 1 2 3 下一页 尾页 3/3/3
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇《从零开始学架构》笔记——第一.. 下一篇SSH框架之Hibernate第二篇

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目