在关闭之前将数据作为客户端发送到 QLocalServer 的问题

Problem with sending data to QLocalServer as a client before closing

我正在学习 Qt,在关闭客户端应用程序之前向 QLocalServer 发送一些数据时遇到了一些问题。在示例中,我尝试发送 "bye" 两次。但在服务器端,我只收到过一次。无论客户端在关闭前发送多少次,服务器都只会收到第一条消息。如果我使用 QCloseEvent,结果是一样的。也许我做错了什么?感谢您的帮助!

简化了 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();
    }

那是 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;
}

您应该使用 waitForBytesWritten() 来确保在关闭套接字之前将数据发送到底层系统缓冲区。

MainWindow::~MainWindow()
{
    QByteArray bye("bye");

    localSocket->write(bye);
    localSocket->write(bye);

    localSocket->waitForBytesWritten(); //<-- wait for data sent out.

    delete ui;
}