Socket vs SocketChannel.open (). Socket ()
What are the advantages / disadvantages of using Channel
Socket
Socket
sourced through SocketChannel.open().socket()
versus traditional Socket
sourced from new Socket()
?
A similar question three years ago ( Any problems replacing the new Socket () with SocketChannel.open (). Socket ()? ) Touches this, but a lot of its information looks outdated. (Tested in Java 8)
My research found these advantages / disadvantages:
Advantages over new Socket()
-
Reading on a socket
InputStream
can be interrupted with a helpThread.interrupt()
, which subsequently also closes the socket and dropsClosedByInterruptionException
. Although it unfortunately closes the socket, I would still have to close it to break out of the read onnew Socket()
, and I would have to separately monitor the socket the stream is bound to. -
Likewise,
Socket.connect()
can be interrupted withThread.interrupt()
, which also results inClosedByInterruptionException
. -
The call
Socket.close()
at the timeSocket.connect()
results inAsynchronousCloseException
, as opposed to the crypticSocketException: Socket operation on nonsocket: connect
one I receive fornew Socket()
.
Advantages over SocketChannel
-
Reading can be disabled with
Socket.setSoTimeout()
. -
Can be completed in
SSLSocket
(withSSLSocketFactory.createSocket(Socket, ...)
) for fast SSL / TLS transition.
Disadvantages over SocketChannel
- Doesn't take advantage of being used
ByteBuf
to reduce copying while reading or writing, so arguably slower in that sense.
Disadvantages over new Socket()
- ???
source to share
No one has answered this question yet
See similar questions:
or similar: