我正在寻找一种方法来避免 StacklessClosedChannelException,但我没有找到任何东西。我想这不安全,也不应该发生,如何避免?
为了避免此类异常,您应该检查通道是否处于活动状态或至少是打开的。有一个布尔验证可以实现这一点。这是 Kotlin 版本:
val f: ChannelFuture = bootstrap.connect(HOST, PORT).sync()
val channel = f.channel()
if (channel?.isActive == true) {
val f: ChannelFuture? = channel?.writeAndFlush(msg)?.sync()
else {
//Channel not even open and therefore it's not writable
}
还有一个
ìsWritable
布尔值,但我没有充分测试它。