本地套接字通信-丢失数据包

时间:2019-02-12 13:11:17

标签: qt

分别使用QLocalServerQLocalSocket创建服务器和客户端类。

服务器:

SocketServer(const QString& name, QObject* prnt=nullptr)
  : QObject(prnt),
    m_server(new QLocalServer(this)),
    m_name(name)
{
  connect(m_server, &QLocalServer::newConnection, this, &SocketServer::handleNewConnection);
}

bool SocketServer::start()
{
   if (!m_server->isListening()) {
     m_server->listen(m_name);
   }
   return m_server->isListening();
}

void SocketServer::handleNewConnection()
{
    QLocalSocket* socket = m_server->nextPendingConnection();
    connect(socket, &QLocalSocket::disconnected, socket, &QLocalSocket::deleteLater);
    connect(socket, &QLocalSocket::readyRead, [&, socket]() {
        QByteArray data(socket->readAll());
        qDebug() << data;        
    });
}

客户端:

QLocalSocket* client = new QLocalSocket(this);
client->setServerName("myServer");    
connect(client, &QLocalSocket::connected, this, [client]() {
  for (int i = 1; i <= 100; ++i) {
        client->write(QStringLiteral("Update status: ") + QString::number(i));
    }
});
client->connectToServer();

在来自客户端的这100条消息中,只有5条或6条出现在服务器端。也在客户端发送消息后尝试调用flush()。我想念什么吗?

0 个答案:

没有答案