一步一步来吧,不可能一口吃成一个胖子.
看不懂大块的代码,至少可以看懂一个小demo,一小部分代码,小demo看的多了,慢慢也就可以看懂更多代码啦.加油!
不要着急啦!
QLocalServer和QLocalSocket单进程和进程通信 - wjbooks - 博客园 (cnblogs.com)
QLocalSocket
1.生成随机数
QT qrand()随机函数-CSDN博客
qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
int num=qrand();
2.QLocalSocket类连接到本地服务器"localserver-test"
QLocalSocket ls;
ls.connectToServer("localserver-test");
3.等待连接到服务器,如果不可以,返回false
ls.waitForConnected()
4.一直循环,向服务器发送随机数(每隔一秒).
while (1){
QTextStream ts(&ls);
ts << QString::number(qrand()) + "\nTTTTTTTTTT" + "\nXXXXXXXX";
ts.flush();
ls.waitForBytesWritten();
sleep(1);
}
QLocalServer
本地服务器,用于本地的进程间通讯
#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
#include <QApplication>
#include <QLabel>
#include <QMessageBox>
#include "widget.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();
}
效果: