This thread对这个话题进行了一些有用的讨论。事实证明,如果(已经)连接成功,则
Socket.isConnected返回true。
从上面的线程:
When you use Socket(), which you seem to have overlooked,
Socket.isConnected() tells you whether Socket.connect() has been called
or not. Similarly for isClosed() and close().
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.
文档说:
Returns true if the socket successfuly connected to a server
而不是一个人可能会期望“如果套接字连接到服务器返回true”。
可以通过查看Socket的来源来确认行为:
public boolean isConnected() {
// Before 1.3 Sockets were always connected during creation
return connected || oldImpl;
}
你也可以运行这个小测试片段:
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
我必须说,文件在这一点上是不清楚的,而且方法名有点误导。