寫個簡單點,比較小白的文檔,言語比較接地氣
Netty是什么?
NIO的高層封裝,NIO很難寫,所以有了Netty,方便異步的操作
service的主要代碼片段
public void run() throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap(); // (2)
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class) // (3)
.childHandler(new ChannelInitializer() { // (4)
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new DiscardServerHandler());
}
})
.option(ChannelOption.SO_BACKLOG, 128) // (5)
.childOption(ChannelOption.SO_KEEPALIVE, true); // (6)
// Bind and start to accept incoming connections.
ChannelFuture f = b.bind(port).sync(); // (7)
// Wait until the server socket is closed.
// In this example, this does not happen, but you can do that to gracefully
// shut down your server.
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
按照代碼順序解釋如下
(1) EventLoopGroup bossGroup = new NioEventLoopGroup();
事件循環隊列,用來接受或發送事件。大家可以把他想象成郵局,消息都要先到郵局,然后再分發出去,郵局維護了一個循環隊列,用來不斷的收信和發信。
(2)ServerBootstrap b = new ServerBootstrap();
啟動服務
(3) b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
開啟了一個通道,這個通道是用來接受連接請求的,管道大家都知道吧,IO里也有,NIO中也有,一切Java中到處都是管道
(4).childHandler(new ChannelInitializer()
這個handler是用來表示響應什么樣的事件的,比如我們這里DiscardServerHandler,隨著程序的復雜,你會加上更多的handle,handler是具體干事的人
(5).option(ChannelOption.SO_BACKLOG, 128)
channel的配置參數,具體可以查手冊
(6).childOption(ChannelOption.SO_KEEPALIVE, true);
option()是 NioServerSocketChannel的配置,childOption()是被parent ServerChannel接受的channel,這里就指的是NioServerSocketChannel
(7)ChannelFuture f = b.bind(port).sync();
綁定端口并開始
再看看我們主要進行事件處理的handle
public class DiscardServerHandler extends ChannelHandlerAdapter { // (1)
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) { // (2)
// Discard the received data silently.
((ByteBuf) msg).release(); // (3)
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (4)
// Close the connection when an exception is raised.
cause.printStackTrace();
ctx.close();
}
}
(1)DiscardServerHandler extends ChannelHandlerAdapter
表示:俺是具體干事的人
(2)我們overrider了 channelRead(),用來讀取接受到的信息
(3)異常處理,懂的...