源代码

https://github.com/coder-xuyong/netty

基础 Server

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
private final ServerBootstrap serverBootstrap = new ServerBootstrap();
private final EventLoopGroup bossGroup = new NioEventLoopGroup(1);
private final EventLoopGroup workerGroup = new NioEventLoopGroup(2);
public NettyServer() {
serverBootstrap
.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel ch) {
ch.pipeline().addLast(new StringDecoder());
}
});
}

public void start(int port) {
ChannelFuture channelFuture = serverBootstrap.bind(port);
channelFuture.addListener(future -> {
if (future.isSuccess()) {
log.info("端口[{}]绑定成功", port);
} else {
log.error("端口[{}]绑定异常!", port);
}
});
try {
// 阻塞在此处,直到绑定端口完成
channelFuture.sync();
} catch (InterruptedException e) {
log.error(e.getMessage());
e.printStackTrace();
}
}