connect() 失败后套接字是否变得不可用? [英] Does socket become unusable after connect() fails?

查看:36
本文介绍了connect() 失败后套接字是否变得不可用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Steven 的The Socket: Networking API, Third Edition"第 4 章第 4.3 段中,作者声明如下

In Chapter 4, paragraph 4.3 of Steven's "The Socket: Networking API, Third Edition", the author states the following

"If connect fails, the socket is no longer usable and must be closed. 
 We cannot call connect again on the socket."

有谁知道上述说法背后的原因吗?

Does anyone know the reason behind the above statement?

在我自己的实验中,我编写了一个简单的 tcp 客户端,它将在主机 A 上运行,一个简单的 tcp 服务器将在主机 B 上运行.tcp 客户端将尝试永远连接到主机 B 上的 tcp 服务器.

In my own experiments, i wrote a simple tcp client, that would run on host A and a simple tcp server, that would run on host B. The tcp client would attempt to connect to the tcp server on Host B forever.

所以,我在主机 B 上启动了服务器.从主机上拔掉了网线.然后我在主机 A 上启动了客户端.在同一个套接字上大约 9 次连接尝试失败后,我只是将网络线重新插入服务器主机.客户端连接成功,愉快地以80K/秒的速度发送消息.

So, i started the server on host B. Pulled the network wire from the host. Then i started the client on host A. After about 9 unsuccessful connect attempts on the same socket, i simply plugged the network wire back into the server host. The client connected successfully and happily sends messages at 80K/sec.

在另一个实验中,在最初成功连接并交换了几百万条消息之后,我从服务器主机上拔掉了电线.然后,几分钟后,我连接了线路,消息流在同一个套接字上恢复.

In yet another experiment, i pulled the wire from the server host, after a initial successful connect and few million messages exchanges after. Then, after few minutes, i connected the wire and message flow resumed on the same socket.

推荐答案

POSIX 2001 在信息部分:

POSIX 2001 says in an informative section:

如果 connect() 失败,则套接字的状态是未指定的.符合标准的应用程序应该在尝试重新连接之前关闭文件描述符并创建一个新的套接字.

If connect() fails, the state of the socket is unspecified. Conforming applications should close the file descriptor and create a new socket before attempting to reconnect.

所以您引用的段落与本规范是一致的.它在您的机器上运行的事实并不意味着您的程序是可移植的.

So the passage you quote is congruent with this specification. The fact it works on your machine does not mean your program is portable.

这篇关于connect() 失败后套接字是否变得不可用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆