2

我正在学习 Qt,并且在关闭客户端应用程序之前向 QLocalServer 发送一些数据时遇到了一些麻烦。在示例中,我尝试发送“再见”两次。但在服务器端,我只收到过一次。无论客户端在关闭前发送多少次,服务器都会收到唯一的第一条消息。如果我使用 QCloseEvent,则结果是相同的。也许我做错了什么?谢谢你的帮助!

简化服务器示例

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

那是客户的例子

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;
}
4

1 回答 1

0

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

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

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

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

    delete ui;
}
于 2018-12-22T00:48:18.070 回答