这篇文章假设你对netty已经有了一点小小的了解,不同于"hello world"的编写,这篇文章叙述的东西更多。其实是在我做完一个netty服务器以后写下的总结。
netty api:http://netty.io/4.1/api/index.html
下载netty之后,可以从这篇文章找到netty的示例源码:https://jingyan.baidu.com/article/358570f64f04c0ce4624fc79.html
好了,接下来我们开始吧
主程序:
public static void main(String[] args) throws Exception {
// 首先是设置EverLoopGroup,parentGroup一般用来接收accpt请求,childGroup用来处理各个连接的请求。
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
EventExecutorGroup executorGroup = new DefaultEventExecutorGroup(16);//耗时任务处理group
ServerBootstrap bootstrap = new ServerBootstrap();
try {
// 添加日志,初始化 BACKLOG用于构造服务端套接字ServerSocket对象,
bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
// 标识当服务器请求处理线程全满时,用于临时存放已完成三次握手的请求的队列的最大长度。
.option(ChannelOption.SO_BACKLOG, 1024).handler(new LoggingHandler(LogLevel.INFO))
// 创建一个新的预测与指定的参数。接收字符串的限度
.childOption(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(64, 1024, 65536))
//使用bytebuf池模式
.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)//关键是这句
.childHandler(new SecureServerInitializer(executorGroup));
// 绑定端口,监听连接
bootstrap.bind(DEFAULT_PORT).sync().channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
这里是初始化的一些操作,比如往pipeline里添加一些新的处理方法,还可以在这里加上解码器和编码器,让自己更专注于自己的业务处理:
public class SecureServerInitializer extends ChannelInitializer<SocketChannel> {
private EventExecutorGroup executorGroup;
public SecureServerInitializer(EventExecutorGroup executorGroup){
this.executorGroup = executorGroup;
}
@Override
protected void initChannel(SocketChannel ch) throws Exception {
// TODO Auto-generated method stub
// 心跳监测<25秒监测一次,如果没收到心跳执行userEventTriggered方法,这个方法在文章后面有写到
ch.pipeline().addLast(new IdleStateHandler(25, 0, 0));
// 添加逻辑处理
ch.pipeline().addLast(executorGroup,new SecureServerHandler());//耗时任务交给其它线程组去做
}
}
这里是具体的处理操作,当然,在这里只是简单的操作,大家在真实使用的时候可以加上更多自己的逻辑。
public class SecureServerHandler extends ChannelInboundHandlerAdapter {
/**
* 当客户端connect成功后,服务端就会接收到这个事件,从而可以把客户端的Channel记录下来,供后面复用
*/
public void channelRead(final ChannelHandlerContext ctx, Object msg) {
ByteBuf buf = (ByteBuf) msg;
byte[] head = new byte[8];
buf.readBytes(buf.readableBytes());
System.out.println(new String("接收到了:" + new String(head)));
ctx.write(Unpooled.copiedBuffer(head));
}
/**
* channelRead执行后触发
*/
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.writeAndFlush(Unpooled.EMPTY_BUFFER); // flush掉所有写回的数据
}
/**
* 通道激活时触发,当客户端connect成功后,服务端就会接收到这个事件
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
// TODO Auto-generated method stub
super.channelActive(ctx);
//这里可以添加上自己的逻辑
}
/**
* 出错时会触发,做一些错误处理
*/
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();// 捕捉异常信息
if (cause instanceof IOException) {// io错误
System.out.println(new Date() + " --------> exception: client is no normal shutdown,address: "
+ ctx.channel().remoteAddress());
ctx.close();
}
}
/**
* 客户端活动超过设定的空闲状态
*/
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent) {
ctx.close();// 关闭连接
if (this.mapId != null) {// 从服务器channel列表移除
ServerReserve.SocketList.remove(this.mapId);
}
} else {
super.userEventTriggered(ctx, evt);
}
}
}
大概就是这样了,大家也可以看看官方api,在收发消息的时候分别有很多encode和decode的类可以在ChannelInitializer的时候加入pipeline帮助大家在接收和发送消息前编码和解码。
官方文档里有很多解码器。这里博主就ByteToMessageDecoder来说一下解码器的使用。
解码器里有一个方法: decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out)
一点小操作:
if (in.readableBytes() < 8)//如果未读满8个字节则返回
return;
返回后解码器会继续等待有字节过来,而不会进入管道的下一个环节,直到满足条件以后out.add(readBytes);
才会进入管道的下一个环节处理。好啦!这里建议大家去了解一下netty的ByteBuf,之后才能更加灵活的处理这些数据的读写。
最后分享一个监测发送的消息是否已经写入网络的方法,在这里当消息写入网络以后我们便将channel关闭。
channel.writeAndFlush(Unpooled.copiedBuffer("you message".getBytes());
ChannelFuture closeFuture = channel.closeFuture();
// 添加监听器监听消息是否已经被写入网络
closeFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture arg0) throws Exception {
// TODO Auto-generated method stub
if (arg0.isSuccess()) {//消息发送成功
channel.close();//关闭channel
}
}
});