DevilKing's blog

冷灯看剑,剑上几分功名?炉香无需计苍生,纵一穿烟逝,万丈云埋,孤阳还照古陵

0%

Simple Netty Tcp Server

原文链接

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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)
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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?