Netty 筆記 -- 記一次消息無法發送

客戶端代碼:



import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;


public class NettyClient {
    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        EventLoopGroup group = new NioEventLoopGroup();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .remoteAddress("localhost", 7113)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInboundHandlerAdapter(){
                    @Override
                    public void channelActive(ChannelHandlerContext ctx) throws Exception {
                        System.out.println(">>>>> 消息發送..");
                        ctx.channel().writeAndFlush("sasaas");
                    }
                });

        try {
            Channel channel = bootstrap.connect().sync().channel();
            ChannelFuture future = channel.closeFuture().sync();
            future.addListener(ChannelFutureListener.CLOSE);
        } catch (InterruptedException e) {

        } finally {
            group.shutdownGracefully();
        }
    }
}

 

服務端代碼:


import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;



public class NettyServer {
    public static void main(String[] args) {
        ServerBootstrap bootstrap = new ServerBootstrap();
        EventLoopGroup group = new NioEventLoopGroup();
        bootstrap.group(group)
                .channel(NioServerSocketChannel.class)
                .childHandler(new LoggingHandler(LogLevel.DEBUG));
        try {
            ChannelFuture future = bootstrap.bind(7113).sync();
            future = future.channel().closeFuture().sync();
        } catch (InterruptedException e) {

        } finally {
            group.shutdownGracefully();
        }
    }
}

 

日誌:

client 日誌>>>>> 消息發送..

server 日誌>>>>

原因:

最後傳輸的消息是bytebuf 或 fileRegion,其他消息不進行發送

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章