【问题标题】:Non-blocking Socket connect always succeeds?非阻塞套接字连接总是成功?
【发布时间】:2016-07-15 04:51:43
【问题描述】:

如果之前有人问过这个问题,我深表歉意。我正在使用选择多路复用编写一个非阻塞套接字客户端。让我感到困惑的一件事是,无论服务器在线还是离线,非阻塞连接总是成功。我搜索了很多帖子并遵循了他们的解决方案,但它们都不能在我的 linux ubuntu 机器上运行。

static void callback_on_select_write(int connect_fd) {

  // Client write event arrived;

  int error = -1;
  socklen_t len = sizeof(error);

  if(getsockopt(connect_fd, SOL_SOCKET, SO_ERROR, &error, &len) == -1) {
    return;
  }

  // getsockopt puts the errno value for connect into erro so 0 means no-error. 
  if(error == 0) {
      // Connection ok.
  }
  else {
    cerr << "Failed to connect\n";
    return;
  }

  // Ready to write/read

}

每次选择返回并调用总是成功的回调,即进入“准备写入/读取”块,而不是导致失败。为什么会发生这种情况?如何设计一个可移植的机制来检测连接是否真的成功?下面是我创建连接器的方式。

int make_socket_client(const ::std::string& hostname, const ::std::string& port) {

  struct addrinfo hints;
  struct addrinfo* res {nullptr};
  struct addrinfo* ptr {nullptr};

  memset(&hints, 0, sizeof(struct addrinfo));
  hints.ai_family = AF_UNSPEC;
  hints.ai_socktype = SOCK_STREAM;
  hints.ai_protocol = IPPROTO_TCP;

  int rv;
  int connector;

  if((rv = getaddrinfo(hostname.c_str(), port.c_str(), &hints, &res)) != 0) {
    return -1;
  }

  // Try to get the first available client connection.
  for(ptr = res; ptr != nullptr; ptr = ptr->ai_next) {

    // Ignore undefined ip type.
    if(ptr->ai_family != AF_INET && ptr->ai_family != AF_INET6) {
      continue;
    }

    // Create a listener socket and bind it to the localhost as the server.
    if((connector = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol)) == -1){
      continue;
    }

    make_fd_nonblocking(connector);

    if(connect(connector, (struct sockaddr*)ptr->ai_addr, ptr->ai_addrlen) < 0) {
      // This is what we expect.
      if(errno == EINPROGRESS) {
        break;
      }
      else {
        close(connector);
        continue;
      }
    }
    else {
      break;
    }
  }

  freeaddrinfo(res);

  if(ptr == nullptr) {
    return -1;
  }

  return connector;  
}

【问题讨论】:

  • 您当然应该查看connect_fd 上的 SO_ERROR 吗? event 是什么?此代码不够完整,无法回答有关问题。
  • 对不起。它应该只是 connect_fd。
  • 原来的connect()返回零了吗?
  • 我发布了另一个关于如何创建非阻塞连接器的代码。
  • 它总是返回带有 errno == EINPROGRESS 的有效连接器。然后我使用 select 来确定它何时可写。

标签: c sockets network-programming nonblocking


【解决方案1】:

每次选择返回并调用这个回调总是 成功,即进入“Ready to write/read”块,而不是 当心失败。为什么会发生这种情况?

当异步 TCP 连接正在进行时(如 connect() 调用中的 -1/EINPROGRESS 所示),您应该将套接字作为其准备写入套接字集的一部分传递给 select(),以便select() 将在套接字指示它准备好写入时返回。

当 TCP 连接成功或失败时,select() 将返回套接字已准备好写入 (*)。发生这种情况时,您需要弄清楚发生了两种可能的结果(成功或失败)中的哪一种。

以下是我在异步连接套接字 select() 准备好写入时调用的函数。

// call this select() has indicated that (fd) is ready-for-write because
// (fd)'s asynchronous-TCP connection has either succeeded or failed.
// Returns true if the connection succeeded, false if the connection failed.
// If this returns true, you can then continue using (fd) as a normal
// connected/non-blocking TCP socket.  If this returns false, you should
// close(fd) because the connection failed.
bool FinalizeAsyncConnect(int fd)
{
#if defined(__FreeBSD__) || defined(BSD)
   // Special case for FreeBSD7, for which send() doesn't do the trick
   struct sockaddr_in junk;
   socklen_t length = sizeof(junk);
   memset(&junk, 0, sizeof(junk));
   return (getpeername(fd, (struct sockaddr *)&junk, &length) == 0);
#else
   // For most platforms, the code below is all we need
   char junk;
   return (send(fd, &junk, 0, 0L) == 0);
#endif
}

(*) 旁注:在 Windows 下,情况略有不同,因为 Windows 喜欢以自己的方式做事:在 Windows 下,如上所述指示异步 connect() 成功,但如果您想收到有关在 Windows 下异步 connect() 尝试失败,您还需要在“except” fd_set 下注册您的套接字,因为它是 Windows 将用于与失败的异步 connect() 通信的“except” fd_set。

【讨论】:

  • 谢谢杰里米。但是,在我的 OSX 系统中,在对等方离线的情况下调用 send 会给我带来 SIGPIPE 错误并且程序退出,并且函数 FinalizeAsyncConnect 永远不会返回。我怎样才能解决这个问题?
  • 通过调用 main() 顶部的 signal(SIGPIPE, SIG_IGN) 禁用 SIGPIPE,如下所述:stackoverflow.com/questions/108183/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-20
  • 2017-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-31
相关资源
最近更新 更多