Alex Spar
Alex Spar

Reputation: 13

Window doesn`t appear because of accept socket function in Qt

I write a program in Qt with raw c++ sockets. The trouble is that my function listen(listener, 1); blocks the showing of main window of the program until it gets any data via the socket. If I delete listen function then the window is shown.

That`s all code that I use:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    int listener, sock;
    struct sockaddr_in addr;
    int bytes_read;

    listener = socket(AF_INET, SOCK_STREAM, 0);

    addr.sin_family = AF_INET;
    addr.sin_port = htons(3366);
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
    bind(listener, (struct sockaddr *)&addr, sizeof(addr));

    listen(listener, 1);

    sock = accept(listener, NULL, NULL);
    char buf[1024];
    bytes_read = recv(sock, buf, 1024, 0);
    ui->label->setText(ui->label->text() + QString(buf));
    ::close(sock);
}

Help me please to show the window straight at the start of the program. Many thanks in advance!

Upvotes: 1

Views: 253

Answers (2)

Your listen call blocks the event loop. If you want to use raw sockets, then to integrate them with Qt you should use the QSocketNotifier to be notified when something interesting happens on a socket, like when a new connection is accepted.

On the other hand, why bother? It's much simpler to use the Qt network module. Here's one answer that shows how easy it is to write an echo server and client.

Upvotes: 1

jhaight
jhaight

Reputation: 299

You should have your GUI code run in a separate thread from your code that handles setting up sockets and listening to connections. You want to have your user interface thread free to handle input from the user and to redraw as necessary. To do this, in your main() you can create a new QThread object which will handle the socket logic.

See the QT documentation on QThreads for how to do this. Below is a link to a SO thread on the topic. what is the correct way to implement a QThread... (example please...)

Upvotes: 1

Related Questions