异步连接和断开epoll的(Linux)的 [英] Async connect and disconnect with epoll (Linux)

查看:914
本文介绍了异步连接和断开epoll的(Linux)的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要异步连接,并使用epoll的为Linux断开连接的TCP客户端。有分机。在Windows功能,如ConnectEx,DisconnectEx,的AcceptEx等...
在TCP服务器标准接受功能正在工作,但在TCP客户端不工作的连接和断开......所有插座是非阻塞。

I need async connect and disconnect for tcp client using epoll for Linux. There are ext. functions in Windows, such as ConnectEx, DisconnectEx, AcceptEx, etc... In tcp server standard accept function is working, but in tcp client doesn't working connect and disconnect... All sockets are nonblocking.

我怎样才能做到这一点?

How can I do this?

谢谢!

推荐答案

要做到非阻塞连接(),假设插座已经作出非阻塞:

To do a non-blocking connect(), assuming the socket has already been made non-blocking:

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
}

有关的第二壳体,其中,连接()与EINPROGRESS失败(只有在这种情况下),则必须等待套接字可写,例如对于epoll的规定,你在等待EPOLLOUT此套接字上。一旦你得到通知,它是可写的(有epoll的,的期望得到一个EPOLLERR或EPOLLHUP事件),检查连接尝试的结果是:

For the second case, where connect() failed with EINPROGRESS (and only in this case), you have to wait for the socket to be writable, e.g. for epoll specify that you're waiting for EPOLLOUT on this socket. Once you get notified that it's writable (with epoll, also expect to get an EPOLLERR or EPOLLHUP event), check the result of the connection attempt:

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上,连接()永远不会立即成功,你总是要等待可写。然而,例如,在FreeBSD,我已经看到了非阻塞connect()以本地主机成功的时候了。

In my experience, on Linux, connect() never immediately succeeds and you always have to wait for writability. However, for example, on FreeBSD, I've seen non-blocking connect() to localhost succeeding right away.

这篇关于异步连接和断开epoll的(Linux)的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆