上一博文我们讲了如何在我们自己的程序中启动第三方的应用程序,并将其加载到我们的界面中,那么加载进来后的第三方应用程序我们如何操作并使用呢,下边我们首先采用TCP的方式讲述我项目中的进程间通信使用:
这里我们使用QT的QTcpServer和QTcpSocket进行服务端和客户端的搭建实现,我们自己的应用程序作为服务端,第三方的程序作为客户端,通过协定的IP和端口号进行连接,具体实现如下:
void Utils::initSocket()
{
m_tcpserver = new QTcpServer(this);
m_tcpsocket = new QTcpSocket(this);
QHostAddress address("127.0.0.1");
bool is = m_tcpserver->listen(address, 8686);//监听的端口号
qDebug() << "-----------------------initSocket listen:" << is;
connect(m_tcpserver, SIGNAL(newConnection()), this, SLOT(newConnect()));
}
void Utils::closeSocket()
{
if (m_tcpsocket) {
m_tcpsocket->abort();
delete m_tcpsocket;
m_tcpsocket = NULL;
}
if (m_tcpserver) {
m_tcpserver->close();
delete m_tcpserver;
m_tcpserver = NULL;
}
qDebug() << "-----------closeSocket";
}
void Utils::newConnect()
{
m_tcpsocket = m_tcpserver->nextPendingConnection();//设置监听
qDebug() << "-----------------------newConnect" << m_tcpsocket;
connect(m_tcpsocket,SIGNAL(readyRead()),
this,SLOT(readMessage())); //服务器接收客户端的消息
connect(m_tcpsocket,SIGNAL(disconnected()),
m_tcpsocket,SLOT(deleteLater()));
}
消息的接受和发送:
void Utils::readMessage()
{
if (!m_tcpsocket || m_tcpsocket->isValid() == false) return;
QString str = m_tcpsocket->readAll();
}
void Utils::sendMessage(QString str)
{
if (str == "" || !m_tcpsocket || m_tcpsocket->isValid() == false) return;
int size = m_tcpsocket->write(str.toUtf8());
m_tcpsocket->flush();
}
此处注意所有接口的封装均已单例的方式实现,方便整个项目中都可以随时进行消息通信。