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

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

问题描述

在史蒂文(Steven)的《套接字:网络API,第三版》的第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/sec的速度发送消息.

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天全站免登陆