Any issues with replacing new Socket() with SocketChannel.open().socket()?

后端 未结 2 1334
独厮守ぢ
独厮守ぢ 2021-01-25 18:03

What can go wrong if I simply replace

socket = new Socket()

with

socket = SocketChannel.open().socket()?

Back

相关标签:
2条回答
  • 2021-01-25 18:26

    There are several.

    1. A Socket acquired via a SocketChannel doesn't appear to support read timeouts.
    2. The InputStream and OutputStream of a socket aren't independent: they have a mutual lock in common.

    Why do you want to interrupt the connect() call? Surely all you want is a connect timeout?

    0 讨论(0)
  • 2021-01-25 18:33

    Differences in the type of thrown exceptions could break existing code.

    For instance, closing a Socket from a different thread while Socket.getInputStream().read() is blocking will result in AsynchronousCloseException after replacing, instead of SocketException that legacy code could be expecting. (AsynchronousCloseException is not a subclass of SocketException.)

    However, Socket.getInputStream().read() will still throw SocketException if the close from the other thread gets in before read().

    0 讨论(0)
提交回复
热议问题