1. 程式人生 > >【Netty4 簡單專案實踐】一、長連線服務通用框架原型

【Netty4 簡單專案實踐】一、長連線服務通用框架原型

    EventLoopGroup bossLoopnew NioEventLoopGroup(); //接收訊息迴圈佇列

    EventLoopGroup workerLoopnew NioEventLoopGroup(); //傳送訊息迴圈佇列

    try{

    ServerBootstrap bootstrap = new ServerBootstrap();

    bootstrap.group(bossLoop, workerLoop) //載入訊息迴圈佇列

        .option(ChannelOption.CONNECT_TIMEOUT_MILLIS

, 3000)

        .option(ChannelOption.TCP_NODELAY, true); //TCP立即發包

    bootstrap.channel(NioServerSocketChannel.class);

    bootstrap.localAddress(new InetSocketAddress(port))

                .childHandler(new ChannelInitializer<Channel>() {

                    @Override

                    protected

void initChannel(Channel ch) throws Exception {

// TODO Auto-generated method stub

                        ChannelPipeline pipeline = ch.pipeline();

pipeline.addLast(new StringDecoder()); //Netty4自帶的String解碼器

                        pipeline.addLast(new StringEncoder()); //Netty4自帶的String編碼器

                        pipeline

.addLast(new MyHandler()); // 自己實現的處理器

                    }

                });

    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);

    ChannelFuture future = bootstrap.bind(port).sync();

    if (future.isSuccess()){}

    future.channel().closeFuture().sync();

} catch (Exception e) {

} finally {

    workerLoop.shutdownGracefully();

    bossLoop.shutdownGracefully();

}

}


file:MyHandler.java

public class ProtoBufHandler extends SimpleChannelInboundHandler<Protocol> { 

    @Override

    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {

        System.out.println(msg);

        ctx.writeAndFlush(msg);

        ctx.close();

    }

}
到此就實現了一個簡單的TCP字串處理程式