Ale*_*der 8 sockets linux asynchronous epoll tcp
我需要使用epoll for Linux为tcp客户端进行异步连接和断开连接.有分机.Windows中的函数,如ConnectEx,DisconnectEx,AcceptEx等...在tcp服务器标准接受函数正在工作,但在tcp客户端无法正常工作连接和断开...所有套接字都是非阻塞的.
我怎样才能做到这一点?
谢谢!
Amb*_*jak 30
要做一个非阻塞的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
}
Run Code Online (Sandbox Code Playgroud)
对于第二种情况,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()
Run Code Online (Sandbox Code Playgroud)
根据我的经验,在Linux上,connect()永远不会立即成功,你总是要等待可写性.但是,例如,在FreeBSD上,我已经看到了对localhost的非阻塞connect()立即成功.