我需要使用适用于 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/