【问题标题】:Browser Connection Reset when using TCPServerwith Qt使用带有 Qt 的 TCPServer 时的浏览器连接重置
【发布时间】:2016-05-02 11:54:24
【问题描述】:

我想为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();
}

【问题讨论】:

  • 您忘记了关于 HTTP 标准的一个非常重要的事情:标题和正文之间的空行。我建议您搜索一个专用的 HTTP 服务器库,这将简化很多其他手动工作。它甚至可能包含简单的路由,因此您可以使用不同的 URL 来给出不同的回复。

标签: c++ qt sockets browser


【解决方案1】:

经过大量的反复试验(和运气),我找到了解决方案。代码应该这样结束 -

...
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();
}

【讨论】:

  • 调用waitForBytesWritten()不是更合适吗?
  • 嗨@FadedCoder,Chrome 中的 ERR_CONNECTION_RESET 相同。刚刚复制了您的解决方案,但 Chrome 每次尝试 3 或 4 次后都会返回一个重置错误...您最后是否采取了其他措施来解决它?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-01
  • 1970-01-01
  • 2014-09-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多