QT 使用QLocalSocke同类进行进程通信遇到的问题(BUG记录)

项目场景:

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();


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值