1

朋友们,

我有一个非阻塞 TCP 套接字(在 AIX 上)。当我尝试 connect() 时,我得到了 EINPROGRESS。我的问题是,如果我在连接完成之前调用 recv(),那么(最合适的)错误代码是什么?

我看到了,万一连接失败,我调用recv(),我得到了ECONNREFUSED;表示我收到了与我之前的 connect() 尝试相对应的错误。采用相同的逻辑,我应该得到 recv() 的 EINPROGRESS。我的方法对吗?

如果是,这会引发另一个问题 - 为什么这样的错误代码不包含在 recv() 的错误代码中?

4

2 回答 2

3

我只看到 EAGAIN 在这种情况下返回,就像您在没有数据可读取的情况下看到的一样。对于写入未连接的套接字,您通常会得到 ENOTCONN,尽管我相信某些平台可能会给您 EAGAIN。

这是一个简单的 Python 脚本来演示:

import socket
# Any address that does not succeed or fail right away will do
ADDR = "192.168.100.100"
PORT = 23
s = socket.socket()
s.setblocking(False)
try:
    s.connect((ADDR, PORT))
except socket.error, e:
    print "Connect gave us",e
try:
    s.recv(1)
except socket.error, e:
    print "Read gave us",e
try:
    s.send("x")
except socket.error, e:
    print "Write gave us",e

对我来说,它给出了: Connect 给了我们(36,'Operation now in progress') Read 给了我们(35,'Resource暂时不可用')Write 给了我们(57,'Socket is not connected')

它们分别是 EINPROGRESS、EAGAIN 和 ENOTCONN。

于 2010-10-31T01:41:36.493 回答
1

您正在一个非阻塞套接字上操作,返回 EINPROGRESS 非常好,这表明连接建立尚未完成,这在连接页面中有记录:

   EINPROGRESS
          The  socket  is  nonblocking  and  the  connection cannot be completed immediately.  It is possible to select(2) or poll(2) for completion by
          selecting the socket for writing.  After select(2) indicates writability, use getsockopt(2) to read the SO_ERROR option at  level  SOL_SOCKET
          to  determine  whether connect() completed successfully (SO_ERROR is zero) or unsuccessfully (SO_ERROR is one of the usual error codes listed
          here, explaining the reason for the failure).

所以你需要选择/池来确保套接字是可写的,并从 SO_ERROR 中得到错误。

于 2015-05-18T02:54:00.170 回答