Skip to content
gqlxj1987's Blog
Go back

Simple Netty Tcp Server

Edit page

原文链接

Channel Pipeline API to build chain of handlers

To perform read and write, Netty provides you Channel Handlers, inbound & outbound. When there is something to read, Channel Inbound Handlers are invoked and when there is something to write, Channel Outbound Handlers are invoked.

class SimpleNettyServerBootstrap {

    void start(int port) throws InterruptedException {
        Utils.log("Starting server at: " + port);
        EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
        EventLoopGroup workerGroup = new NioEventLoopGroup();// (2)
        try {
            ServerBootstrap b = new ServerBootstrap();// (3)
            b.group(bossGroup, workerGroup) // (4)
                    .channel(NioServerSocketChannel.class)// (5)
                    .childHandler(new SimpleTCPChannelInitializer())// (6)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);// (7)

            // Bind and start to accept incoming connections.
            ChannelFuture f = b.bind(port).sync();// (8)
            if(f.isSuccess()) Utils.log("Server started successfully"); // (9)
            f.channel().closeFuture().sync(); // (10)
        } finally {
            Utils.log("Stopping server");
            workerGroup.shutdownGracefully();// (11)
            bossGroup.shutdownGracefully();// (12)
        }
    }
}
public class SimpleTCPChannelHandler extends SimpleChannelInboundHandler<String> {

 @Override
 public void channelActive(ChannelHandlerContext ctx) {
   Utils.log(ctx.channel().remoteAddress(), "Channel Active");
 }

 @Override
 protected void channelRead0(ChannelHandlerContext ctx, String s) throws Exception {
   Utils.log(ctx.channel().remoteAddress(), s);// (1)
   ctx.channel().writeAndFlush("Thanks\n"); // (2)
 }

 @Override
 public void channelInactive(ChannelHandlerContext ctx) {
   Utils.log(ctx.channel().remoteAddress(), "Channel Inactive");
 }
}

Tcp非全双工的,You can’t directly send or receive objects over TCP channel. You have to convert from bytes to object while reading and from objects to bytes while writing?


Edit page
Share this post on:

Previous Post
Rudr Intro
Next Post
Use Jshell