java - Netty的future.channel().closeFuture().sync();到底有什么用?
問題描述
我看到很多Netty的例子都在末尾加上了這句話:future.channel().closeFuture().sync();
比如:
public class TimeServer { private int count = 0; public void bind(int port) {try { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workGroup = new NioEventLoopGroup(); ServerBootstrap b = new ServerBootstrap(); // (2) b.group(bossGroup, workGroup).channel(NioServerSocketChannel.class) // (3) .childHandler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel arg0) throws Exception { arg0.pipeline().addLast(new LineBasedFrameDecoder(1024)); arg0.pipeline().addLast(new StringDecoder()); arg0.pipeline().addLast(new ChannelInboundHandlerAdapter() {@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // ByteBuf buf = (ByteBuf) msg; // byte[] req = new // byte[buf.readableBytes()]; // buf.readBytes(req); // String body = new String(req, 'UTF-8'); System.out.println( 'The Time Server Received order:' + msg + '; the counter is:' + ++count); // String currentTime = 'QUERY TIME // ORDER'.equalsIgnoreCase(body) // ? new // Date(System.currentTimeMillis()).toString() // : 'BAD ORDER'; // // currentTime = currentTime + // System.getProperty('line.separator'); // ByteBuf resp = // Unpooled.copiedBuffer(currentTime.getBytes()); // ctx.writeAndFlush(resp);} });} }); ChannelFuture future = b.bind(port).sync(); System.out.println('Server start listen at ' + port); future.channel().closeFuture().sync();System.out.println('執行到這里 ' + port);} catch (InterruptedException e) { e.printStackTrace();} } public static void main(String[] args) {new TimeServer().bind(10000); }}
但是我看這行代碼一直沒有執行。請問這是怎么回事呢?
問題解答
回答1:不是沒執行,是主線程到這里就 wait 子線程退出了,子線程才是真正監聽和接受請求的。
相關文章:
1. 老哥們求助啊2. tp6表單令牌3. django - 后臺返回的json數據經過Base64加密,獲取時用python如何解密~!4. 我在centos容器里安裝docker,也就是在容器里安裝容器,報錯了?5. 我的html頁面一提交,網頁便顯示出了我的php代碼,求問是什么原因?6. docker 17.03 怎么配置 registry mirror ?7. node.js - node 客戶端socket一直報錯Error: read ECONNRESET,用php的socket沒問題哈。。8. node.js - nodejs中把熱request保存下來,使用JSON.stringify(req)報錯,請問怎么解決?9. javascript - canvas 可以實現 PS 魔法橡皮擦的功能嗎?10. angular.js - 如何通俗易懂的解釋“依賴注入”?
