linux - 异步连接和断开与 epoll (Linux)

标签 linux sockets asynchronous tcp epoll

我需要使用适用于 Linux 的 epoll 为 tcp 客户端进行异步连接和断开连接。有分机。 Windows 中的函数,例如 ConnectEx、DisconnectEx、AcceptEx 等... 在 tcp 服务器标准接受函数中工作,但在 tcp 客户端中不工作连接和断开连接...所有套接字都是非阻塞的。

我该怎么做?

谢谢!

最佳答案

要执行非阻塞 connect(),假设套接字已经变为非阻塞:

int res = connect(fd, ...);
if (res < 0 && errno != EINPROGRESS) {
    // error, fail somehow, close socket
    return;
}

if (res == 0) {
    // connection has succeeded immediately
} else {
    // connection attempt is in progress
}

对于第二种情况,connect() 因 EINPROGRESS 而失败(并且仅在这种情况下),您必须等待套接字可写,例如对于 epoll,指定您正在等待此套接字上的 EPOLLOUT。一旦您收到它可写的通知(使用 epoll,期望获得 EPOLLERR 或 EPOLLHUP 事件),检查连接尝试的结果:

int result;
socklen_t result_len = sizeof(result);
if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &result, &result_len) < 0) {
    // error, fail somehow, close socket
    return;
}

if (result != 0) {
    // connection failed; error code is in 'result'
    return;
}

// socket is ready for read()/write()

根据我的经验,在 Linux 上,connect() 永远不会立即成功,您总是必须等待可写性。但是,例如,在 FreeBSD 上,我看到非阻塞的 connect() 到 localhost 立即成功。

关于linux - 异步连接和断开与 epoll (Linux),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10187347/

相关文章:

java - 如何使用 sched_setaffinity 清除线程关联性,这意味着我想将控制权交还给内核?

java - 在Java中使用Winsock "send"函数(或类似函数)

c# - CS1998 "method lacks await operators"背后的原因是什么

asynchronous - F# 中异步操作的顺序执行链接

node.js - express/node,理解渲染模板和异步模型

linux - 在 bash 中读取和比较 .txt 文件中的列

linux - 如何设置 bashrc bash_profile

linux - 如何将 linux 用户限制为 SSH 的绝对最小命令

c++ - 从远程服务器接收数据

c - 在套接字中使用 offsetof() 而不是 sizeof() 有什么区别吗?