JAVA为什么关闭套接字_java – 如何连接和关闭套接字?

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

我必须说,文件在这一点上是不清楚的,而且方法名有点误导。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值