使用 QTcpSocket 时出错

Error while using QTcpSocket

我正在创建一个(非常基本的)MJPG 服务器来在浏览器上显示网络摄像头数据。到目前为止,我已经部分做到了。

这是我的代码:

TcpServer::TcpServer(QObject *parent) :
QObject(parent)
{
server = new QTcpServer(this);
// whenever a user connects, it will emit signal
connect(server, SIGNAL(newConnection()),
    this, SLOT(newConnection()));
if (!server->listen(QHostAddress::Any, 9999))
    qDebug() << "Server could not start";
else
    qDebug() << "Server started!";
}
...
void TcpServer::newConnection()
{
QTcpSocket *socket = server->nextPendingConnection();
QByteArray ContentType = ("HTTP/1.0 200 OK\r\n" \
    "Cache-Control: no-cache\r\n" \
    "Cache-Control: private\r\n" \
    "Content-Type: multipart/x-mixed-replace;boundary=--boundary\r\n");
socket->write(ContentType);
std::vector<uchar> buff;
Mat img; //OpenCV Material
while (1) {
    // Image to Byte Array via OPENCV Method
    buff.clear();buff.empty();
    vCapture->read(img); //Read from webcam

    imencode(".jpg", img, buff, compression_params);
    std::string content(buff.begin(), buff.end());
    QByteArray CurrentImg(QByteArray::fromStdString(content));
    QByteArray BoundaryString = ("--boundary\r\n" \
        "Content-Type: image/jpeg\r\n" \
        "Content-Length: ");
    BoundaryString.append(QString::number(CurrentImg.length()));
    BoundaryString.append("\r\n\r\n");

    socket->write(BoundaryString);
    socket->write(CurrentImg); // Write The Encoded Image
    socket->flush();
}

}

问题-

当我运行这个程序时,显示第一张图片。之后app上不断打印如下错误-

QIODevice::write (QTcpSocket): device not open

看起来套接字已关闭,所以我重新初始化了套接字,就像这样 - socket = server->nextPendingConnection();,尽管应用程序抛出了此代码的错误。关于如何解决此问题的任何帮助?

编辑 -

我试过 lambda 方法,效果很好。然而,我仍然面临两个问题 -

  1. 图像尺寸必须过小(大约 270x480,JPG 质量最低)

  2. (更重要) 我必须手动按下浏览器上的重新加载按钮来重新加载图像,它不会自动从一张图像更改为其他.

It looked like the socket got closed

与其猜测,不如连接到 TCPServerTCPSocket 的错误信号,以了解何时发生错误或客户端何时断开连接。

您遇到的问题是 while(1) 循环。 Qt 是一个 event-driven 框架,因此在主线程上的无限循环中的代码将阻止传递事件。

连接到 QTcpSocket::readyRead 信号并在调用连接的插槽时处理数据,而不是无限循环。

Qt 使用 Fortune Server and Fortune Client 示例代码对此进行了演示。

如果您使用的是 C++ 11,则可以使用与 lambda 函数的连接来处理 readyRead,就像这样

void TcpServer::newConnection()
{
    ...

    QTcpSocket *m_TcpHttpClient = server->nextPendingConnection();
    connect(m_TcpHttpClient, &QTcpSocket::readyRead, [=](){

        // handle received data here

    });

}

这是我在 中用来打开 MJPEG 流媒体服务器的代码。也许它可以帮助您找出您的问题。

void MjpegStreamingEngine::StartServer(){

    m_TcpHttpServer = new QTcpServer();

    m_TcpHttpServer->connect(m_TcpHttpServer,
                             SIGNAL(newConnection()),
                             this,
                             SLOT(TcpHttpconnected()));

    m_TcpHttpServer->listen(QHostAddress::Any,
                            8889);
}

void MjpegStreamingEngine::TcpHttpconnected(){

    m_TcpHttpClient = m_TcpHttpServer->nextPendingConnection();

    m_TcpHttpClient->connect(m_TcpHttpClient,
                             SIGNAL(readyRead()),
                             this,
                             SLOT(TcpHttpreadyRead()));

}

void MjpegStreamingEngine::TcpHttpreadyRead(){

    m_TcpHttpClient->readAll(); // Discard "Get Request String"

    QByteArray ContentType = ("HTTP/1.0 200 OK\r\n" \
                              "Server: en.code-bude.net example server\r\n" \
                              "Cache-Control: no-cache\r\n" \
                              "Cache-Control: private\r\n" \
                              "Content-Type: multipart/x-mixed-replace;boundary=--boundary\r\n\r\n");

    m_TcpHttpClient->write(ContentType);


    while(1){

        if (m_TcpHttpClient->isOpen())
        {

            // Send Image

            QThread::msleep(10);

        }else{
            return;
        }

    }

    m_TcpHttpClient->disconnect(); //Should never be Reached
}