使用TCPServerwith Qt

时间:2016-05-02 11:54:24

标签: c++ qt sockets browser

我想为MJPEGs创建一个服务器,我找到了这个教程:http://www.bogotobogo.com/Qt/Qt5_QTcpServer_Client_Server.php。但是,当我从像Chrome这样的Web浏览器进行连接时(Microsoft Telnet工作正常),它会显示连接重置。

创建服务器后,我想在我的浏览器上显示MJPEGs(就像IP相机一样):How to Create a HTTP MJPEG Streaming Server With QTcp-Server Sockets?

这是我的 Server.cpp(稍加修改) -

#include "stdafx.h"
#include "TCPServer.h"

TcpServer::TcpServer(QObject *parent) :
QObject(parent)
{
    server = new QTcpServer(this);
    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 header = "HTTP/1.1 200 OK\r\n";
    socket->write(header);
    QByteArray ContentType = "Content-Type: text/html\r\n";
    socket->write(ContentType);
    QByteArray Body = "Test";
    socket->write(Body);
    socket->flush();
    socket->close();
}

1 个答案:

答案 0 :(得分:0)

经过大量的试验和错误(以及运气)后,我找到了解决方案。代码应该像这样结束 -

...
socket->flush();
socket->waitForBytesWritten(10000);
socket->close();

编辑 -

再次尝试后,我发现了这一点 - 标题后应该有一个额外的\r\n。所以这将有效 -

void TcpServer::newConnection()
{
QTcpSocket *socket = server->nextPendingConnection();
QByteArray header = "HTTP/1.1 200 OK\r\n";
socket->write(header);
QByteArray ContentType = "Content-Type: text/html\r\n\r\n\*Here is the edit*\";
socket->write(ContentType);
QByteArray Body = "Test";
socket->write(Body);
socket->flush();
socket->close();
}