Search code examples
qtqlocalsocketqlocalserver

Problem with sending data to QLocalServer as a client before closing


I'm learning Qt and having some troubles with sending some data to QLocalServer before closing the client application. In the example i've tried to send "bye" twice. But on server side i've recieved it only once. No matter how many times client will send if before closing, the server will recieve the only first message. If i use QCloseEvent the rusult is the same. Maybe i'm doing something wrong? Thank's for any help!

Simplified the example of Server

MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
        server = new QLocalServer(this);
        server->listen("Server1");
        connect(server, SIGNAL(newConnection()), this, SLOT(processNewConnection()));

    }


    void MainWindow::processNewConnection()
    {
       clientConnection = new QLocalSocket(this);
       clientConnection = server->nextPendingConnection();
       connect(clientConnection,SIGNAL(readyRead()), this, SLOT(proceessData()));
    }

    void MainWindow::proceessData()
    {
        QLocalSocket* clientSocket = (QLocalSocket*)sender();
        QByteArray recievedData;
        recievedData = clientSocket -> readAll();
    }

Thats example of Client

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    localSocket = new QLocalSocket(this);
    localSocket -> connectToServer("Server1");
    QByteArray hey("Hey");
    localSocket->write(hey);
}

MainWindow::~MainWindow()
{
    QByteArray bye("bye");
    localSocket->write(bye);
    localSocket->write(bye);
    delete ui;
}

Solution

  • You should use waitForBytesWritten() to make sure that data is sent to the underlying system buffer before closing the socket.

    MainWindow::~MainWindow()
    {
        QByteArray bye("bye");
    
        localSocket->write(bye);
        localSocket->write(bye);
    
        localSocket->waitForBytesWritten(); //<-- wait for data sent out.
    
        delete ui;
    }