分别使用QLocalServer
和QLocalSocket
创建服务器和客户端类。
服务器:
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()
。我想念什么吗?