熟悉了使用java nio编程的套路,实际上就跟底层socket的没啥区别。
下面学习如何使用Netty编写简单的Time Server。
代码:https://github.com/NearXdu/NettyLearn
public class TimeServer {
public void bind(int port) throws Exception{
//配置服务端的NIO线程组
//
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try{
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup,workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG,1024)
.childHandler(new ChildChannelHandler());
//绑定端口,同步等待成功
ChannelFuture f = b.bind(port).sync();
//等待服务端监听端口关闭
f.channel().closeFuture().sync();
}finally {
//释放线程池资源
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
private class ChildChannelHandler extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new TimeServerHandler());
}
}
public static void main(String[] args) throws Exception{
int port =1025;
if(args!=null && args.length>0){
try{
port =Integer.valueOf(args[0]);
}catch (NumberFormatException e){
}
}
new TimeServer().bind(port);
}
}
1.NioEventLoopGroup
:Reactor线程组,用于处理网络事件。
2.ServerBootstrap
:Netty用于启动NIO服务端的辅助启动类。
3.ServerBootstrap
的group
方法设置监听套接字NioServerSocketChannel
设置BACKLOG,设置IO事件的处理类ChildChannelHandler
4.ServerBootstrap
的bind
方法绑定监听端口
在Handler类中,有些区别就是netty4和netty5的API会有些出入,在书中继承ChannelHandlerAdapter,我用的是Netty4,因此需要稍微改写:
public class TimeServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
throws Exception {
ByteBuf buf = (ByteBuf) msg;//read buff
byte[] req = new byte[buf.readableBytes()];//通过readble获取到大小
buf.readBytes(req);//readByte将数据塞入req中
//业务
String body = new String(req, "UTF-8");
System.out.println("The time server receive order : " + body);
String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body.trim()) ? new java.util.Date(
System.currentTimeMillis()).toString() : "BAD ORDER";
//构造响应
ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
//发送
ctx.write(resp);
}
}
这个方法就有点类似muduo中onMessage,或者libevent中onRead回调了,数据通过参数传递,并使用封装的缓存接收,最后构造业务响应。
参考:
1) netty权威指南
2) http://stackoverflow.com/questions/24844042/extends-channelhandleradapter-but-does-not-override-or-implement-a-method-from