日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪(fǎng)問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

Netty 中 IOException: Connection reset by peer 与 java.nio.channels.ClosedChannelException: null

發(fā)布時(shí)間:2023/12/10 编程问答 41 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Netty 中 IOException: Connection reset by peer 与 java.nio.channels.ClosedChannelException: null 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

最近發(fā)現(xiàn)系統(tǒng)中出現(xiàn)了很多 IOException: Connection reset by peer 與 ClosedChannelException: null

深入看了看代碼, 做了些測(cè)試, 發(fā)現(xiàn) Connection reset 會(huì)在客戶(hù)端不知道 channel 被關(guān)閉的情況下, 觸發(fā)了 eventloop 的 unsafe.read() 操作拋出

而 ClosedChannelException 一般是由 Netty 主動(dòng)拋出的, 在 AbstractChannel 以及 SSLHandler 里都可以看到 ClosedChannel 相關(guān)的代碼

AbstractChannel?

static final ClosedChannelException CLOSED_CHANNEL_EXCEPTION = new ClosedChannelException();...static {CLOSED_CHANNEL_EXCEPTION.setStackTrace(EmptyArrays.EMPTY_STACK_TRACE);NOT_YET_CONNECTED_EXCEPTION.setStackTrace(EmptyArrays.EMPTY_STACK_TRACE);}...@Overridepublic void write(Object msg, ChannelPromise promise) {ChannelOutboundBuffer outboundBuffer = this.outboundBuffer;if (outboundBuffer == null) {// If the outboundBuffer is null we know the channel was closed and so// need to fail the future right away. If it is not null the handling of the rest// will be done in flush0()// See https://github.com/netty/netty/issues/2362 safeSetFailure(promise, CLOSED_CHANNEL_EXCEPTION);// release message now to prevent resource-leak ReferenceCountUtil.release(msg);return;}outboundBuffer.addMessage(msg, promise);}

在代碼的許多部分, 都會(huì)有這個(gè) ClosedChannelException, 大概的意思是說(shuō)在 channel close 以后, 如果還調(diào)用了 write 方法, 則會(huì)將 write 的 future 設(shè)置為 failure, 并將 cause 設(shè)置為 ClosedChannelException, 同樣 SSLHandler 中也類(lèi)似

-----------------

回到 Connection reset by peer, 要模擬這個(gè)情況比較簡(jiǎn)單, 就是在 server 端設(shè)置一個(gè)在 channelActive 的時(shí)候就 close channel 的 handler. 而在 client 端則寫(xiě)一個(gè) Connect 成功后立即發(fā)送請(qǐng)求數(shù)據(jù)的 listener. 如下

client

public static void main(String[] args) throws IOException, InterruptedException {Bootstrap b = new Bootstrap();b.group(new NioEventLoopGroup()).channel(NioSocketChannel.class).handler(new ChannelInitializer<NioSocketChannel>() {@Overrideprotected void initChannel(NioSocketChannel ch) throws Exception {}});b.connect("localhost", 8090).addListener(new ChannelFutureListener() {@Overridepublic void operationComplete(ChannelFuture future) throws Exception {if (future.isSuccess()) {future.channel().write(Unpooled.buffer().writeBytes("123".getBytes()));future.channel().flush();}}});

server

public class SimpleServer {public static void main(String[] args) throws Exception {EventLoopGroup bossGroup = new NioEventLoopGroup(1);EventLoopGroup workerGroup = new NioEventLoopGroup();ServerBootstrap b = new ServerBootstrap();b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_REUSEADDR, true).childHandler(new ChannelInitializer<NioSocketChannel>() {@Overrideprotected void initChannel(NioSocketChannel ch) throws Exception {ch.pipeline().addLast(new SimpleServerHandler());}});b.bind(8090).sync().channel().closeFuture().sync();} }public class SimpleServerHandler extends ChannelInboundHandlerAdapter {@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {ctx.channel().close().sync();}@Overridepublic void channelRead(ChannelHandlerContext ctx, final Object msg) throws Exception {System.out.println(123);}@Overridepublic void channelInactive(ChannelHandlerContext ctx) throws Exception {System.out.println("inactive");} }

?

這種情況之所以能觸發(fā) connection reset by peer 異常, 是因?yàn)?connect 成功以后, client 段先會(huì)觸發(fā) connect 成功的 listener, 這個(gè)時(shí)候 server 段雖然斷開(kāi)了 channel, 也觸發(fā) channel 斷開(kāi)的事件 (它會(huì)觸發(fā)一個(gè)客戶(hù)端 read 事件, 但是這個(gè) read 會(huì)返回 -1, -1 代表 channel 關(guān)閉, client 的 channelInactive 跟 channel ?active 狀態(tài)的改變都是在這時(shí)發(fā)生的), 但是這個(gè)事件是在 connect 成功的 listener 之后執(zhí)行, 所以這個(gè)時(shí)候 listener 里的 channel 并不知道自己已經(jīng)斷開(kāi), 它還是會(huì)繼續(xù)進(jìn)行 write 跟 flush 操作, 在調(diào)用 flush 后, eventloop 會(huì)進(jìn)入 OP_READ 事件里, 這時(shí)候 unsafe.read() 就會(huì)拋出 connection reset 異常. eventloop 代碼如下

NioEventLoop

private static void processSelectedKey(SelectionKey k, AbstractNioChannel ch) {final NioUnsafe unsafe = ch.unsafe();if (!k.isValid()) {// close the channel if the key is not valid anymore unsafe.close(unsafe.voidPromise());return;}try {int readyOps = k.readyOps();// Also check for readOps of 0 to workaround possible JDK bug which may otherwise lead// to a spin loopif ((readyOps & (SelectionKey.OP_READ | SelectionKey.OP_ACCEPT)) != 0 || readyOps == 0) {unsafe.read();if (!ch.isOpen()) {// Connection already closed - no need to handle write. return;}}if ((readyOps & SelectionKey.OP_WRITE) != 0) {// Call forceFlush which will also take care of clear the OP_WRITE once there is nothing left to write ch.unsafe().forceFlush();}if ((readyOps & SelectionKey.OP_CONNECT) != 0) {// remove OP_CONNECT as otherwise Selector.select(..) will always return without blocking// See https://github.com/netty/netty/issues/924int ops = k.interestOps();ops &= ~SelectionKey.OP_CONNECT;k.interestOps(ops);unsafe.finishConnect();}} catch (CancelledKeyException e) {unsafe.close(unsafe.voidPromise());}}

這就是 connection reset by peer 產(chǎn)生的原因

------------------

再來(lái)看 ClosedChannelException 如何產(chǎn)生, 要復(fù)現(xiàn)他也很簡(jiǎn)單. 首先要明確, 并沒(méi)有客戶(hù)端主動(dòng)關(guān)閉才會(huì)出現(xiàn) ClosedChannelException 這么一說(shuō). 下面來(lái)看兩種出現(xiàn) ClosedChannelException 的客戶(hù)端寫(xiě)法

client 1, 主動(dòng)關(guān)閉 channel

public class SimpleClient {private static final Logger logger = LoggerFactory.getLogger(SimpleClient.class);public static void main(String[] args) throws IOException, InterruptedException {Bootstrap b = new Bootstrap();b.group(new NioEventLoopGroup()).channel(NioSocketChannel.class).handler(new ChannelInitializer<NioSocketChannel>() {@Overrideprotected void initChannel(NioSocketChannel ch) throws Exception {}});b.connect("localhost", 8090).addListener(new ChannelFutureListener() {@Overridepublic void operationComplete(ChannelFuture future) throws Exception {if (future.isSuccess()) { future.channel().close();future.channel().write(Unpooled.buffer().writeBytes("123".getBytes())).addListener(new ChannelFutureListener() {@Overridepublic void operationComplete(ChannelFuture future) throws Exception {if (!future.isSuccess()) {logger.error("Error", future.cause());}}});future.channel().flush();}}});} }

?

只要在 write 之前主動(dòng)調(diào)用了 close, 那么 write 必然會(huì)知道 close 是 close 狀態(tài), 最后 write 就會(huì)失敗, 并且 future 里的 cause 就是 ClosedChannelException

--------------------

client 2. 由服務(wù)端造成的 ClosedChannelException

public class SimpleClient {private static final Logger logger = LoggerFactory.getLogger(SimpleClient.class);public static void main(String[] args) throws IOException, InterruptedException {Bootstrap b = new Bootstrap();b.group(new NioEventLoopGroup()).channel(NioSocketChannel.class).handler(new ChannelInitializer<NioSocketChannel>() {@Overrideprotected void initChannel(NioSocketChannel ch) throws Exception {}});Channel channel = b.connect("localhost", 8090).sync().channel();Thread.sleep(3000);channel.writeAndFlush(Unpooled.buffer().writeBytes("123".getBytes())).addListener(new ChannelFutureListener() {@Overridepublic void operationComplete(ChannelFuture future) throws Exception {if (!future.isSuccess()) {logger.error("error", future.cause());}}});} }

服務(wù)端

public class SimpleServer {public static void main(String[] args) throws Exception {EventLoopGroup bossGroup = new NioEventLoopGroup(1);EventLoopGroup workerGroup = new NioEventLoopGroup();ServerBootstrap b = new ServerBootstrap();b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_REUSEADDR, true).childHandler(new ChannelInitializer<NioSocketChannel>() {@Overrideprotected void initChannel(NioSocketChannel ch) throws Exception {ch.pipeline().addLast(new SimpleServerHandler());}});b.bind(8090).sync().channel().closeFuture().sync();} }

這種情況下, ?服務(wù)端將 channel 關(guān)閉, 客戶(hù)端先 sleep, 這期間 client 的 eventLoop 會(huì)處理客戶(hù)端關(guān)閉的時(shí)間, 也就是 eventLoop 的 processKey 方法會(huì)進(jìn)入 OP_READ, 然后 read 出來(lái)一個(gè) -1, 最后觸發(fā) client channelInactive 事件, 當(dāng) sleep 醒來(lái)以后, 客戶(hù)端調(diào)用 writeAndFlush, 這時(shí)候客戶(hù)端 channel 的狀態(tài)已經(jīng)變?yōu)榱?inactive, 所以 write 失敗, cause 為 ClosedChannelException

轉(zhuǎn)載于:https://www.cnblogs.com/zemliu/p/3864131.html

創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來(lái)咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)

總結(jié)

以上是生活随笔為你收集整理的Netty 中 IOException: Connection reset by peer 与 java.nio.channels.ClosedChannelException: null的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。