QLocalServer和QLocalSocket单进程和进程通信实例

参考博客:http://tgstdj.blog.163.com/blog/static/74820040201243072238780/

1. 建立一个QLocalServer实例 m_server2. 进行listen :

m_server->listen("servername")

3. 当有连接到来时,QLocalServer会发送netConnection()信号,所以进行信号连接,在init()函数中:

connect(m_server, SIGNAL(newConnection()),this, SLOT(newConnection()));

4.在newConnection()函数中取得连接客户端的QLocalSocket

QLocalSocket *newsocket =m_server->nextPendingConnection();

5.当QLocalSocket可以读数据时它会发送readyRead()信号,所以对newsocket进行信号连接,在newConnection()函数中:

 connect(newsocket,SIGNAL(readyRead()), this, SLOT(readyRead()));

6.在readyRead()函数中读取数据:

// 取得是哪个localsocket可以读数据了

QLocalSocket *local = static_cast(sender());

if (!local)

return;

QTextStream in(local);

QString readMsg;

// 读出数据

readMsg = in.readAll();


全部代码, QT新建一个项目,主窗口mainwindow。

server.h:(尖括号替换为了引号,因为新浪里尖括号无法直接打出)
#ifndefSERVER_H

#define SERVER_H


#include "QObject"

#include "QtNetwork/QLocalServer"

#include "QtNetwork/QLocalSocket"

#include "QString"

#include "QTextStream"


class Server : public QObject

{

Q_OBJECT

public:

explicit Server(QObject *parent = 0);

~Server();

int init(const QString & servername);


private:

int isServerRun(const QString & servername);

QLocalServer *m_server;


signals:

void newMessage(const QString &msg);


public slots:

void newConnection();

void readyRead();

};


#endif // SERVER_H



server.cpp:
#include "server.h"
 
Server::Server(QObject *parent) :
 QObject(parent)
{
 m_server = 0;
}
 
Server::~Server()
{
 if (m_server)
  delete m_server;
}

int Server::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;
}
 
void Server::newConnection()
{
//有新连接来了
 QLocalSocket *newsocket =m_server->nextPendingConnection();connect(newsocket,SIGNAL(readyRead()),this,SLOT(readyRead()));
}

void Server::readyRead()
{
//取得是哪个localsocket可以读数据了
 QLocalSocket *local =static_cast(sender());
 if (!local)
 return ;
QTextStream in(local);
 QString readMsg;
 //读出数据
 readMsg = in.readAll();
 //发送收到数据信号
 emit newMessage(readMsg);
}

int Server::isServerRun(const QString &servername)
{
//判断是否有一个同名的服务器在运行
 QLocalSocket ls;
 ls.connectToServer(servername);
if (ls.waitForConnected(1000))
{
//已经在运行
 ls.disconnectFromServer()
; ls.close();
 return 1;
}

return 0;
}


main.cpp:
#include"mainwindow.h"
#include "QApplication"
#include "QLabel"
#include "QMessageBox"
#include "server.h"
#include "QObject"

 
int main(int argc, char *argv[])
{
 QApplication a(argc, argv);
QLabel text("test");
 Server s;
 if (!s.init("localserver-test"))
 {
//初始化失败,说明已经有一个服务在运行
 QMessageBox::information(&text,"info","Thereis already exist one!");
 return 1;
 }
 
QObject::connect(&s,SIGNAL(newMessage(const QString&)),&text,SLOT(setText(const QString &)));text.show();
 
return a.exec();
}


工程结构:
QLocalServer和QLocalSocket单进程和进程通信实例

客户端测试:
main.cpp:

#include "mainwindow.h"
#include "QApplication"
#include "QtNetwork/QLocalSocket"
#include "stdlib.h"
#include "unistd.h"
 
  
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
 
  
    QLocalSocket ls;
    ls.connectToServer("localserver-test");
    srand(1000);
    if (ls.waitForConnected())
    {
        while(1)
        {
            QTextStream ts(&ls);
            ts<<QString::number(rand()) + "\nTTTTTTTTTTT" + "\nXXXXXXXXXXX";
            ts.flush();
            ls.waitForBytesWritten();
            sleep(1);
        }
    }
    MainWindow w;
    w.show();
 
  
    return a.exec();
}
 
 

要在Qt的QLocalServer和QLocalSocket之间相互发送消息,您需要遵循以下步骤: 1. 在QLocalServer中,使用`newConnection()`信号来接受来自客户端的新连接,并在连接成功时创建一个QLocalSocket实例,并保存该实例以便稍后使用。 2. 在QLocalSocket中,使用`connected()`信号来检测与服务器的连接是否成功,并在连接成功时使用`write()`函数向服务器发送消息。 3. 在QLocalServer中,使用`readyRead()`信号来检测来自客户端的消息,并使用`readAll()`函数读取所有可用的字节数据。 4. 在QLocalSocket中,使用`readyRead()`信号来检测来自服务器的消息,并使用`readAll()`函数读取所有可用的字节数据。 下面是一个简的示例代码,演示如何在QLocalServer和QLocalSocket之间相互发送消息: ```cpp // Server QLocalSocket *clientConnection; QLocalServer *server = new QLocalServer(this); if (!server->listen("myserver")) { qDebug() << "Unable to start the server: " << server->errorString(); return; } // accept new connections connect(server, &QLocalServer::newConnection, [&](){ clientConnection = server->nextPendingConnection(); }); // handle incoming messages from client connect(clientConnection, &QLocalSocket::readyRead, [&](){ QByteArray message = clientConnection->readAll(); qDebug() << "Received message from client: " << message; }); // Client QLocalSocket *socket = new QLocalSocket(this); // connect to the server socket->connectToServer("myserver"); // handle connection success connect(socket, &QLocalSocket::connected, [&](){ qDebug() << "Connected to server"; socket->write("Hello from client"); }); // handle incoming messages from server connect(socket, &QLocalSocket::readyRead, [&](){ QByteArray message = socket->readAll(); qDebug() << "Received message from server: " << message; }); ``` 这里我们在QLocalServer中监听名为“myserver”的本地套接字,并在`newConnection()`信号中接受新连接。在客户端连接成功后,我们使用`write()`函数向服务器发送消息。在QLocalServer中,我们使用`readyRead()`信号来检测来自客户端的消息,并使用`readAll()`函数读取所有可用的字节数据。在QLocalSocket中,我们使用`readyRead()`信号来检测来自服务器的消息,并使用`readAll()`函数读取所有可用的字节数据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值