NIO 框架Netty4.x 整体流程和使用

这篇文章假设你对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
				}
			}
		});
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
2023-07-13 09:15:56,872 WARN org.apache.flink.runtime.dispatcher.DispatcherRestEndpoint [] - Unhandled exception java.io.IOException: Connection reset by peer at sun.nio.ch.FileDispatcherImpl.read0(Native Method) ~[?:1.8.0_372] at sun.nio.ch.SocketDispatcher.read(SocketDispatcher.java:39) ~[?:1.8.0_372] at sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:223) ~[?:1.8.0_372] at sun.nio.ch.IOUtil.read(IOUtil.java:192) ~[?:1.8.0_372] at sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:379) ~[?:1.8.0_372] at org.apache.flink.shaded.netty4.io.netty.buffer.PooledByteBuf.setBytes(PooledByteBuf.java:253) ~[flink-dist-1.15.3.jar:1.15.3] at org.apache.flink.shaded.netty4.io.netty.buffer.AbstractByteBuf.writeBytes(AbstractByteBuf.java:1132) ~[flink-dist-1.15.3.jar:1.15.3] at org.apache.flink.shaded.netty4.io.netty.channel.socket.nio.NioSocketChannel.doReadBytes(NioSocketChannel.java:350) ~[flink-dist-1.15.3.jar:1.15.3] at org.apache.flink.shaded.netty4.io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:151) [flink-dist-1.15.3.jar:1.15.3] at org.apache.flink.shaded.netty4.io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:719) [flink-dist-1.15.3.jar:1.15.3] at org.apache.flink.shaded.netty4.io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:655) [flink-dist-1.15.3.jar:1.15.3] at org.apache.flink.shaded.netty4.io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:581) [flink-dist-1.15.3.jar:1.15.3] at org.apache.flink.shaded.netty4.io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:493) [flink-dist-1.15.3.jar:1.15.3] at org.apache.flink.shaded.netty4.io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:986) [flink-dist-1.15.3.jar:1.15.3] at org.apache.flink.shaded.netty4.io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74) [flink-dist-1.15.3.jar:1.15.3] at java.lang.Thread.run(Thread.java:750) [?:1.8.0_372]
最新发布
07-14

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值