Linux, sockets, non-blocking connect

前端 未结 3 620
北海茫月
北海茫月 2020-12-25 14:42

I want to create a non-blocking connect. Like this:

socket.connect(); // returns immediately

For this, I use another thread, an infinite lo

3条回答
  •  孤城傲影
    2020-12-25 15:07

    You should use the following steps for an async connect:

    • create socket with socket(..., SOCK_NONBLOCK, ...)
    • start connection with connect(fd, ...)
    • if return value is neither 0 nor EINPROGRESS, then abort with error
    • wait until fd is signalled as ready for output
    • check status of socket with getsockopt(fd, SOL_SOCKET, SO_ERROR, ...)
    • done

    No loops - unless you want to handle EINTR.

    If the client is started first, you should see the error ECONNREFUSED in the last step. If this happens, close the socket and start from the beginning.

    It is difficult to tell what's wrong with your code, without seeing more details. I suppose, that you do not abort on errors in your check_socket operation.

提交回复
热议问题