熟悉了使用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
Netty TimeServer 实现
本文介绍了使用Netty实现简单的TimeServer的过程。首先配置服务端NIO线程组,然后利用ServerBootstrap设置监听端口及事件处理类。通过自定义TimeServerHandler处理客户端请求并返回当前时间。
使用Netty编程&spm=1001.2101.3001.5002&articleId=72624862&d=1&t=3&u=7241573caf964092a59adca139bbcca9)
1158

被折叠的 条评论
为什么被折叠?



