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 help Thread.interrupt()

    , which subsequently also closes the socket and drops ClosedByInterruptionException

    . Although it unfortunately closes the socket, I would still have to close it to break out of the read on new Socket()

    , and I would have to separately monitor the socket the stream is bound to.

  • Likewise, Socket.connect()

    can be interrupted with Thread.interrupt()

    , which also results in ClosedByInterruptionException

    .

  • The call Socket.close()

    at the time Socket.connect()

    results in AsynchronousCloseException

    , as opposed to the cryptic SocketException: Socket operation on nonsocket: connect

    one I receive for new Socket()

    .

Advantages over SocketChannel

  • Reading can be disabled with Socket.setSoTimeout()

    .

  • Can be completed in SSLSocket

    (with SSLSocketFactory.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()

  • ???
+3


source to share





All Articles