问题描述
我使用的是 Java 套接字客户端.如果服务器仍然连接到我的客户端,但它没有发送对我的消息的响应 - 我最终会收到读取超时异常.
I'm using a Java socket client. In a case where the server is still connected to my client but it does not send a response to my message - I eventually get a read time out exception.
在这种情况下,我想测试一下我是否应该重新连接我的套接字或只是保留它以重复使用它.
In that case I want to test to see if I should reconnect my socket or just keep it an re-use it.
我使用这个条件:
if (!socket.isConnected() || socket.isClosed() || !socket.isBound()) {
try {
socket.close();
} catch (IOException e1) {
}
// Wait on a new connection
socket = connectSocket(.....);
}
但我似乎总是重新连接.当我记录布尔属性的值时,我看到:
But I always seem to reconnect. When I log the values of the Boolean properties I see this:
connected: true 关闭: true bound: true
connected: true closed: true bound: true
如何连接和关闭?
TIA
推荐答案
这个主题 有一些关于这个主题的有用讨论.事实证明,Socket.isConnected
如果(曾经)成功连接,则返回 true.
This thread has some useful discussions on this topic. It turns out that Socket.isConnected
returns true if it has (ever) been successfully connected.
来自上面的线程:
当您使用 Socket()
时,您似乎忽略了这一点,Socket.isConnected()
告诉你 Socket.connect()
是否已经被调用或不.isClosed()
和 close()
类似.
对这些方法的混淆是由于混淆了socket,在应用程序的控制之下,带有状态整个连接,这是在协议的控制之下.isConnected()
和 isClosed()
告诉你你对套接字做了什么.除了用于确定状态的读写之外,没有其他 API连接.
Confusion over these methods results from confusing the state of the socket, which is under the control of the application, with the state of the overall connection, which is under the control of the protocol. isConnected()
and isClosed()
tell what you have done to the socket. There are no APIs other than read and write for determining the state of the connection.
文档说:
如果套接字成功连接到服务器,则返回真
而不是人们可能期望的如果套接字连接到服务器,则返回 true".
and not as one perhaps would expect "returns true if the socket is connected to a server".
行为可以通过查看Socket的来源来确认:
The behavior can be confirmed by looking at the source of Socket:
public boolean isConnected() {
// Before 1.3 Sockets were always connected during creation
return connected || oldImpl;
}
您也可以运行这个小测试片段:
You could also run this little test snippet:
Socket s = new Socket();
System.out.println("isConnected: " + s.isConnected() +
" isBound: " + s.isBound() +
" isClosed: " + s.isClosed());
s.connect(new InetSocketAddress("google.com", 80));
System.out.println("isConnected: " + s.isConnected() +
" isBound: " + s.isBound() +
" isClosed: " + s.isClosed());
s.close();
System.out.println("isConnected: " + s.isConnected() +
" isBound: " + s.isBound() +
" isClosed: " + s.isClosed());
打印:
isConnected: false isBound: false isClosed: false
isConnected: true isBound: true isClosed: false
isConnected: true isBound: true isClosed: true
我必须说文档在这一点上很不清楚,而且方法名称有点误导.
I must say that the documentation is quite unclear on this point, and that the method-name is a bit misleading.
这篇关于套接字如何既连接又关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!