Accept socket connection in background while displaying Qt GUI in C++

  asynchronous, c++, qt, serversocket, sockets

My problem

This function is supposed to accept() a connection from a client and return the new file descriptor newfd. The problem is that waiting for a connection freezes the Qt GUI.

int tcp_connect(int sockfd)
{
    struct sockaddr_storage client_addr;
    socklen_t sin_size = sizeof client_addr;
    int newfd = accept(sockfd, (struct sockaddr *)&client_addr, &sin_size);

    return newfd;
}

My attempts

I’ve tried executing the function asynchronously using std::async, but the user interface still freezes until a connection from a client is accepted.

std::future<int> future (std::async(tcp_connect, sockfd));
int newfd = future.get();

I have also tried using QTConcurrent::run, but it yields the same result.

QFuture<int> future = QtConcurrent::run(tcp_connect, sockfd);
int newfd = future.result();

Let me know if further information is required to answer the question.

Source: Windows Questions C++

LEAVE A COMMENT