netty报错:远程主机强迫关闭了一个现有的连接。(已解决)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yqwang75457/article/details/83587688

昨天,java 集成netty服务的项目,在测试服务器上,发现了一个问题:

1.项目netty包版本:netty-all-5.0.0.Alpha1.jar。

2.问题的描述:服务器启动,各种通信正常,运行一段时间,大概10分钟后,这个问题就出现了,并且客户端发送上来的数据,不再收到回写数据,感觉就是被卡死了。

3.错误信息如下:

java.io.IOException: 你的主机中的软件中止了一个已建立的连接。
	at sun.nio.ch.SocketDispatcher.read0(Native Method)
	at sun.nio.ch.SocketDispatcher.read(SocketDispatcher.java:43)
	at sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:223)
	at sun.nio.ch.IOUtil.read(IOUtil.java:192)
	at sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:379)
	at io.netty.buffer.UnpooledUnsafeDirectByteBuf.setBytes(UnpooledUnsafeDirectByteBuf.java:446)
	at io.netty.buffer.AbstractByteBuf.writeBytes(AbstractByteBuf.java:871)
	at io.netty.channel.socket.nio.NioSocketChannel.doReadBytes(NioSocketChannel.java:208)
	at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:119)
	at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:485)
	at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:452)
	at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:346)
	at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:794)
	at java.lang.Thread.run(Thread.java:745)

(找了很多博客,都没能解决到问题,但是从各个博文中,我就感觉我代码依然是有问题的。)

直到今天,终于解决了!!!!

最后我是这样解决的(我始终感觉我犯的是一个低级的错误,真的是恨自己。):

1.找到你读取通道数据的方法:public void channelRead(ChannelHandlerContext ctx, Object msg)。

2.检查这个方法中的代码,我这里是由于没有添加ctx.flush()导致出错:

我这里加上后,netty通信正常。

Tips:下面这2个方法,也需要flush()或者close()

	/**
	 * channelReadComplete channel 通道 Read 读取 Complete 完成
	 * 在通道读取完成后会在这个方法里通知,对应可以做刷新操作 ctx.flush()
	 */
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		ctx.flush();
	}

	/**
	 * exceptionCaught exception 异常 Caught 抓住
	 * 抓住异常,当发生异常的时候,可以做一些相应的处理,比如打印日志、关闭链接
	 */
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		//super.exceptionCaught(ctx, cause);
		ctx.close();
		log.error("异常信息:", cause);
		System.out.println("异常信息:\r\n" + cause.getMessage());
		
	}

猜你喜欢

转载自blog.csdn.net/yqwang75457/article/details/83587688