Qt 中QTcpServer(接上一篇)

xiaoxiao2021-03-01  34

Qt 支持信号与信号的传输

在helloWorld类中建立:    

server = new DaemonTcpServer(this);     connect(server, SIGNAL(newRequest(DaemonTcpRequest*, DaemonTcpResponse*)),             this, SLOT(handleRequest(DaemonTcpRequest*, DaemonTcpResponse*)));

在DaemonTcpServer类中建立:

DaemonTcpConnection *connection =  new DaemonTcpConnection(m_tcpServer->nextPendingConnection(), this); connect(connection, SIGNAL(newRequest(DaemonTcpRequest *, DaemonTcpResponse *)),                 this, SIGNAL(newRequest(DaemonTcpRequest *, DaemonTcpResponse *)));

 

这样QTcpSocket触发

connect(socket, SIGNAL(readyRead()), this, SLOT(parseRequest()));

的是时候,

在DaemonTcpConnection中调用:

Q_EMIT this->newRequest(this->m_request, response);

DaemonTcpConnection.newRequest  ——>DaemonTcpServer.newRequest  ——>helloWorld中的槽handleRequest

这样就把DaemonTcpConnection中建立的两个对象的指针m_request,和response传给了

void HelloWorld::handleRequest(DaemonTcpRequest *req, DaemonTcpResponse *resp) {       //delete req       //Q_UNUSED(req);       QString data = req->GetData();       if (data != "")       {           FifoThread *write = new FifoThread(data);           connect(write, SIGNAL(finished()), write, SLOT(deleteLater()));           write->start();           //req->end();           QByteArray body = "Hello World";           resp->setHeader("Content-Length", QString::number(body.size()));           resp->writeHead(200);           resp->end(body);       }       else {           QByteArray body = "Get dirverName error";           resp->setHeader("Content-Length", QString::number(body.size()));           resp->writeHead(200);           resp->end(body);       } }

 

最后自己总结一下:

    connect(DaemonTcpServer, SIGNAL(newRequest(DaemonTcpRequest*, DaemonTcpResponse*)),             HelloWorld, SLOT(handleRequest(DaemonTcpRequest*, DaemonTcpResponse*)));

connect(DaemonTcpConnection , SIGNAL(newRequest(DaemonTcpRequest *, DaemonTcpResponse *)),                 DaemonTcpServer, SIGNAL(newRequest(DaemonTcpRequest *, DaemonTcpResponse *)));

DaemonTcpConnection中调用

Q_EMIT this->newRequest(request, response);

把自己内部的两个对象最后封装给外部使用,

DaemonTcpRequest 和DaemonTcpResponse 中会操作DaemonTcpConnection

DaemonTcpConnection中也会有DaemonTcpRequest和DaemonTcpResponse

有循环引用,不过却很灵活

转载请注明原文地址: https://www.6miu.com/read-3450112.html

最新回复(0)