简体   繁体   English

用 SocketChannel.open().socket() 替换 new Socket() 有什么问题吗?

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

What can go wrong if I simply replace如果我简单地更换会出什么问题

socket = new Socket()

with

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

Background: I have some legacy code using new Socket() , and I wanted to be able to interrupt the socket.connect() call.背景:我有一些使用new Socket()遗留代码,我希望能够中断socket.connect()调用。 I don't want to rewrite the code to use NIO.我不想重写代码来使用 NIO。 I learned that Thread.interrupt() does not interrupt socket.connect() , but that socket.close() on another thread is supposed to interrupt the connection.我了解到Thread.interrupt()不会中断socket.connect() ,但是另一个线程上的socket.close()应该中断连接。 Oddly, that worked with Java 7 but not Java 6.奇怪的是,这适用于 Java 7 但不适用于 Java 6。

I somehow got it into my head that using socket = SocketChannel().open().socket() would magically allow me to use Thread.interrupt() to interrupt socket.connect() .我以某种方式让我想到使用socket = SocketChannel().open().socket()会神奇地允许我使用Thread.interrupt()来中断socket.connect() It doesn't, but oddly, it does make socket.close() interrupt socket.connect() in Java 6 too!它没有,但奇怪的是,它确实使 Java 6 中的socket.close()中断socket.connect()

Note that I'm not directly using the attached SocketChannel in any way---it appears when I create the Socket and never again.请注意,我没有以任何方式直接使用附加的SocketChannel ---它在我创建Socket时出现并且再也不会出现。

What can go wrong with this?这有什么问题?

There are several.有几种。

  1. A Socket acquired via a SocketChannel doesn't appear to support read timeouts.通过 SocketChannel 获取的 Socket 似乎不支持读取超时。
  2. The InputStream and OutputStream of a socket aren't independent: they have a mutual lock in common.套接字的 InputStream 和 OutputStream 不是独立的:它们有共同的互锁。

Why do you want to interrupt the connect() call?为什么要中断connect() 调用? Surely all you want is a connect timeout?当然你想要的只是连接超时?

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.例如,在Socket.getInputStream().read()阻塞时关闭来自不同线程的Socket将在替换后导致AsynchronousCloseException ,而不是遗留代码可能期望的SocketException ( AsynchronousCloseException is not a subclass of SocketException .) AsynchronousCloseException不是SocketException的子类。)

However, Socket.getInputStream().read() will still throw SocketException if the close from the other thread gets in before read() .但是,如果来自其他线程的关闭在read()之前进入, Socket.getInputStream().read()仍将抛出SocketException

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM