关闭Java NIO套接字通道而不关闭基础TCP套接字

问题描述 投票:0回答:1

关闭特定的ChannelSocket实际上也会关闭TCP套接字。即使keep-alive设置为true。

val socketChannel = selectionKey.channel().asInstanceOf[SocketChannel]

socketChannel.socket().setKeepAlive(true)

socketChannel.close()

println("Socket closed?", socketChannel.socket().isClosed) // prints true

我只想关闭套接字通道,以便不想在此通道上收听更多事件。但是我想保持连接打开。

scala sockets nio
1个回答
0
投票

我能够使用每个interestOps上可用的SelectionKey方法解决此问题。

如果您不想再听其他事件,可以使用interestOps(0)

val socketChannel = selectionKey.channel().asInstanceOf[SocketChannel]

socketChannel.socket().setKeepAlive(true)
// socketChannel.close()

selectionKey.interestOps(0) // Stops listening on events

println("Socket closed?", socketChannel.socket().isClosed) // prints false
© www.soinside.com 2019 - 2024. All rights reserved.