🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] ## 概述 QLocalServer 1. QLocalServer可以接受来自本地socket的连接。 2. server通过调用listen(),监听特定的连接。 3. newConnection()是在每次server与client连接上时所发出的信号。 4. nextPendingConnection()将等待中的连接当作一个已连接上的**QLocalSocket**。返回值是指向QLocalSocket的指针,这个QLocalSocket可以与client建立通信。 ## 示例 <details> <summary> server.h</summary> ``` #ifndef SERVER_H #define SERVER_H #include <QLocalServer> #include <QLocalSocket> class Server : public QObject { Q_OBJECT public: Server() { m_server = 0; } ~Server() { if (m_server) { delete m_server; } } int init(const QString & servername) { // 如果已经有一个实例在运行了就返回0 if (isServerRun(servername)) { return 0; } m_server = new QLocalServer; // 先移除原来存在的,如果不移除那么如果 // servername已经存在就会listen失败 QLocalServer::removeServer(servername); // 进行监听 m_server->listen(servername); connect(m_server, SIGNAL(newConnection()), this, SLOT(newConnection())); return 1; } private slots: // 有新的连接来了 void newConnection() { QLocalSocket *newsocket = m_server->nextPendingConnection(); connect(newsocket, SIGNAL(readyRead()), this, SLOT(readyRead())); } // 可以读数据了 void readyRead() { // 取得是哪个localsocket可以读数据了 QLocalSocket *local = static_cast<QLocalSocket *>(sender()); if (!local) return; QTextStream in(local); QString readMsg; // 读出数据 readMsg = in.readAll(); // 发送收到数据信号 emit newMessage(readMsg); } private: // 判断是否有一个同名的服务器在运行 int isServerRun(const QString & servername) { // 用一个localsocket去连一下,如果能连上就说明 // 有一个在运行了 QLocalSocket ls; ls.connectToServer(servername); if (ls.waitForConnected(1000)){ // 说明已经在运行了 ls.disconnectFromServer(); ls.close(); return 1; } return 0; } signals: void newMessage(const QString &msg); private: QLocalServer *m_server; }; #endif // SERVER_H ``` </details> <br /> <details> <summary> server_main.cpp</summary> ``` #include <QApplication> #include <QLabel> #include <QMessageBox> #include "server.h" int main(int argc, char **argv) { QApplication app(argc, argv); QLabel text("teststts"); Server s; if (!s.init("localserver-test")){ // 初使化失败, 说明已经有一个在运行了 QMessageBox::information(&text, "info", "There is already exist one!"); return 1; } QObject::connect(&s, SIGNAL(newMessage(const QString &)),&text, SLOT(setText(const QString &))); text.show(); return app.exec(); } ``` </details> <br /> <details> <summary> client.cpp</summary> ``` #include <QLocalSocket> #include <stdlib.h> #include <unistd.h> int main(int argc, char **argv) { QLocalSocket ls; ls.connectToServer("localserver-test"); srandom(1000); if (ls.waitForConnected()){ while (1){ QTextStream ts(&ls); ts << QString::number(random()) + "\nTTTTTTTTTT" + "\nXXXXXXXX"; ts.flush(); ls.waitForBytesWritten(); sleep(1); } } return 0; } ``` </details> <br />