项目场景:
QT上位机开发
问题描述
在开发过程中需要使用到进程间通信
进程间通信刚刚开始想要使用文件,经过了解大部分都是使用的QLocalSocket 进行通信的。
刚开是思路,想要将QLocalSocket 封装成一个类,初始化、监听、和新的链接到达都在一个函数内。
但是后来发现,封装成一个类后,主函数进行调用,有新的客户端到达时,并不会出发newConnect()的信号。无法进行通信
原因分析:
提示:这里填写问题的分析:
原因目前未知,主要时没有事件进行研究。
解决方案:
将QLocalSocket,QLocalServer的初始化,监听,发送信息,全部放入主线程。(进程间通信成功!)
void MainWindow::initProcessCommunication(){
m_server=new QLocalServer(this);
connect(m_server,SIGNAL(newConnection()),this,SLOT(slotnewConnection()));
QLocalServer::removeServer("myServer"); //删除已有的连接
m_server->listen("myServer");
}
void MainWindow::slotnewConnection(){
if (m_server->hasPendingConnections())
{
//获取新的连接对象
m_socket = m_server->nextPendingConnection();
//捕获客户端发送数据的信号
connect(m_socket,SIGNAL(readyRead()),this,SLOT(slotreadData()));
//捕获客户端断开的信号
connect(m_socket,SIGNAL(disconnected()),this,SLOT(slotdisconnect()));
//捕获连接中的错误信息
connect(m_socket,SIGNAL(error(QLocalSocket::LocalSocketError)),this,SLOT(sloterror(QLocalSocket::LocalSocketError)));
m_localSocketList.append(m_socket);
qDebug()<<m_localSocketList.size();
}
}
void MainWindow::slotdisconnect(){
for(int i = 0; i < m_localSocketList.size(); i++)
{
if(m_localSocketList.at(i)->state() != QLocalSocket::ConnectedState)
{
m_localSocketList.at(i)->deleteLater();
m_localSocketList.removeAt(i);
}
}
qDebug()<<"socket heve disconnected";
}
void MainWindow::sloterror(QLocalSocket::LocalSocketError error){
qDebug()<<"process put error:"<<error;
}
void MainWindow::writeProcessData(QString str){
qDebug()<<"check connect";
if(m_socket->state()==QLocalSocket::ConnectedState){
m_socket->write(str.toLocal8Bit());
}
}
void MainWindow::closeThisServer(){
//销毁所有接收到的客户端对象和信号槽
for (int i = 0; i < m_localSocketList.size(); ++i)
{
disconnect(m_localSocketList.at(i),SIGNAL(readyRead()),this,SLOT(slotreadData()));
disconnect(m_localSocketList.at(i),SIGNAL(disconnected()),this,SLOT(slotdisconnect()));
disconnect(m_localSocketList.at(i),SIGNAL(error(QLocalSocket::LocalSocketError)),this,SLOT(sloterror(QLocalSocket::LocalSocketError)));
m_localSocketList.at(i)->abort(); //断开连接
m_localSocketList.at(i)->deleteLater();
}
//关闭服务器
m_server->close();
m_localSocketList.clear();
}