Error while using QTcpSocket
<p>I am creating a (very basic) <code>MJPG</code> server to show webcam data on a browser. I have partly managed to do it so far.</p>

<p>Here is my code:</p>

<pre><code>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-&gt;listen(QHostAddress::Any, 9999))
    qDebug() &lt;&lt; "Server could not start";
else
    qDebug() &lt;&lt; "Server started!";
}
...
void TcpServer::newConnection()
{
QTcpSocket *socket = server-&gt;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-&gt;write(ContentType);
std::vector&lt;uchar&gt; buff;
Mat img; //OpenCV Material
while (1) {
    // Image to Byte Array via OPENCV Method
    buff.clear();buff.empty();
    vCapture-&gt;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-&gt;write(BoundaryString);
    socket-&gt;write(CurrentImg); // Write The Encoded Image
    socket-&gt;flush();
}
</code></pre>

<p>}</p>

<p><strong>The Problem -</strong> </p>

<p>When I run this program, the first image is shown. After that, the following error is continuously printed on the app -</p>

<pre><code>QIODevice::write (QTcpSocket): device not open
</code></pre>

<p>It looked like the socket got closed, so I used re-initialized the socket, like this - <code>socket = server-&gt;nextPendingConnection();</code>, although the app threw an error with this code. Any help on how to fix this?</p>

<p><strong>EDIT -</strong></p>

<p>I tried the lambda method and it worked fine. However, <strong>I still face 2 problems</strong> -</p>

<ol>
<li><p>The image size has to be excessively low (around 270x480 with lowest JPG quality)</p></li>
<li><p>(<strong>MORE IMPORTANT</strong>) I have to manually press the reload button on browser to reload the image, it doesn't automatically change from one image to the other.</p></li>
</ol>