Andy Sukowski-Bang
Andy Sukowski-Bang

Reputation: 1420

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

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.

Upvotes: 0

Views: 299

Answers (1)

mugiseyebrows
mugiseyebrows

Reputation: 4698

Qt has QTcpSocket with asyncronous signal-slot api, you can use that. Or you can use QThread.

Upvotes: 1

Related Questions