【问题标题】:ClosedChannelException after sending async message and then closing channel发送异步消息然后关闭通道后的 ClosedChannelException
【发布时间】:2011-12-20 23:04:05
【问题描述】:

当我从客户端异步发送消息然后关闭通道时,Netty 抛出以下异常。

java.nio.channels.ClosedChannelException
at sun.nio.ch.SocketChannelImpl.ensureWriteOpen(SocketChannelImpl.java:133)
at sun.nio.ch.SocketChannelImpl.write(SocketChannelImpl.java:324)
at org.jboss.netty.channel.socket.nio.SocketSendBufferPool$PooledSendBuffer.transferTo(SocketSendBufferPool.java:239)
at org.jboss.netty.channel.socket.nio.NioWorker.write0(NioWorker.java:469)
at org.jboss.netty.channel.socket.nio.NioWorker.writeFromTaskLoop(NioWorker.java:392)
at org.jboss.netty.channel.socket.nio.NioSocketChannel$WriteTask.run(NioSocketChannel.java:276)
at org.jboss.netty.channel.socket.nio.NioWorker.processWriteTaskQueue(NioWorker.java:268)
at org.jboss.netty.channel.socket.nio.NioWorker.run(NioWorker.java:199)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)

我的发送代码如下:

Channels.write(clientChannel, messageObject);

我的关闭代码如下:

    ChannelGroupFuture future = ALL_CHANNELS.close();
    future.awaitUninterruptibly();
    if (null != clientBootstrap) {
        clientBootstrap.releaseExternalResources();
    }

在关闭之前我需要做些什么来刷新通道吗?

【问题讨论】:

    标签: netty


    【解决方案1】:

    我遇到了类似的问题。我的解决方法是关闭写入返回的ChannelFuture

    ChannelFuture f = clientChannel.write(messageObject);
    f.addListener(ChannelFutureListener.CLOSE);
    

    希望这对你有用。

    【讨论】:

    • 优秀。这困扰了我好几天。我发现的 Netty 示例都没有这样做。
    • 很快就没有谈过。这没有用。由于通道已关闭,后续消息发送现在失败。
    • 我认为您只需要在完成发送/接收时关闭通道 - 即在最后一次写入之后。
    【解决方案2】:

    抱歉,我不明白您的问题。您现在在写入完成后关闭通道(就像 Veebs 建议的那样),现在您抱怨通道关闭时新写入失败?如果您需要更多然后写入操作,则需要将 ChannelFutureListener.CLOSE 添加到返回的最后一个未来。

    希望对你有帮助..

    【讨论】:

      猜你喜欢
      • 2013-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-13
      • 2011-04-05
      相关资源
      最近更新 更多