2

I want to create a Server for MJPEGs and I found this tutorial: http://www.bogotobogo.com/Qt/Qt5_QTcpServer_Client_Server.php. But when I connect from a Web Browser like Chrome (Microsoft Telnet works fine), it shows connection reset.

After creating the server, I would like to show MJPEGs on my browser (like an IP Camera does) using this: How to Create a HTTP MJPEG Streaming Server With QTcp-Server Sockets?

Here's my Server.cpp (A little modified) -

#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();
}
Community
  • 1
  • 1
FadedCoder
  • 1,517
  • 1
  • 16
  • 36
  • 1
    You forget a very important thing regarding the HTTP standard: The empty line between the headers and the body. I suggest you to search for a dedicated HTTP server library which will simplify quite a lot of otherwise manual work. It might even contain simple routing so you can have different URLs that give different replies. – Some programmer dude May 02 '16 at 12:57

1 Answers1

1

After LOTS of trial and error (and luck), I found the solution. The code should end like this -

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

EDIT -

After trying again, I found out this - There should be an extra \r\n after the headers. So this will work -

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();
}
FadedCoder
  • 1,517
  • 1
  • 16
  • 36
  • 1
    Wouldn't it be more appropriate to call waitForBytesWritten() instead? – RobbieE May 03 '16 at 08:54
  • Hi @FadedCoder, same ERR_CONNECTION_RESET here in Chrome. Just copied your solution, but Chrome keeps returning reset errors one from each 3 or 4 tries... Did you do anything else to solve it in the end? – andcl Jan 05 '21 at 13:24