添加到QList的QTcpSockets似乎从列表中消失了

时间:2019-05-20 16:12:40

标签: c++ qt5 qlist qtcpsocket qtcpserver

我正在创建QTcpServer,以将MJPEG流发送到连接到服务器的客户端。当我从服务器收到newConnection信号时,将QTcpSocket添加到QList。然后,另一个函数获取帧,并查看QList是否为非空。问题在于,即使我建立了连接,从另一个函数的角度来看,QList仍然为空。

我这样设置QTcpServer:

  server = new QTcpServer(this);

  connect(server, SIGNAL(newConnection()), this, SLOT(newConnection()));

然后在每个新连接上:

void 
MjpegServer::newConnection() {

    if(!socketMutex.tryLock(1000)) {
        qCritical() << "Could not lock sendFrame Mutex to add new client";
        return;
    }

    while(server->hasPendingConnections()) {
        qInfo() << "Got new MJPEG Connection";
        m_clients.append(server->nextPendingConnection());

        QByteArray ContentType = ("HTTP/1.0 200 OK\r\n" \
            "Cache-Control: no-cache\r\n" \
            "Pragma: no-cache\r\n" \
            "Connection: close\r\n" \
            "Content-Type: multipart/x-mixed-replace; boundary=mjpegstream\r\n\r\n");
        m_clients.last()->write(ContentType);
        m_clients.last()->flush();
        m_clients.last()->waitForBytesWritten(3000);

        connect(m_clients.last(), &QTcpSocket::disconnected, this, &MjpegServer::socketDisconnected);
        connect(m_clients.last(), SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(onSocketStateChanged(QAbstractSocket::SocketState)));

        qInfo() << "Clients now connected: " + QString::number(m_clients.count());
    }

    socketMutex.unlock();
}

运行代码并连接客户端时,我得到一个打印输出,说m_clients.count()为1。我有一个发送视频帧的函数:

void
MjpegServer::sendFrame(Mat &img) {

    if(!socketMutex.tryLock(1000)) {
        qCritical() << "Could not lock sendFrame Mutex";
        return;
    }

    // Only encode if there are connected clients
    if(m_clients.count() == 0) {
        socketMutex.unlock();
        qInfo() << "No clients";
        return;
    }

    qInfo() << "Encoding image";
    std::vector<uchar> outbuf;
    std::vector<int> params;
    params.push_back(CV_IMWRITE_JPEG_QUALITY);
    params.push_back(100);
    imencode(".jpg", img, outbuf, params);

    std::string content(outbuf.begin(), outbuf.end());
    QByteArray CurrentImg(QByteArray::fromStdString(content));
    QByteArray BoundaryString = ("--mjpegstream\r\nContent-Type: image/jpeg\r\nContent-Length: ");
    BoundaryString.append(QString::number(CurrentImg.length()));
    BoundaryString.append("\r\n\r\n");

    for( int i=0; i < m_clients.count(); ++i ) {
        qInfo() << "Writing data to client " + QString::number(i);
        QTcpSocket* socket = m_clients.at(i);
        socket->write(BoundaryString);
        socket->write(CurrentImg); // Write The Encoded Image
        socket->flush();
    }
    socketMutex.unlock();
}

现在,此选项仅打印“无客户”。即使客户端已连接。当QTcpSockets断开连接或它们的状态改变时,我也有连接到监视器的信号,这些信号不会触发。 QTcpSockets连接,似乎没有断开连接,但是sendFrame函数无法在QList中看到它们。

任何帮助将不胜感激...

0 个答案:

没有答案