Error while using QTcpSocket

前端 未结 2 1296
暗喜
暗喜 2020-12-20 07:59

I am creating a (very basic) MJPG server to show webcam data on a browser. I have partly managed to do it so far.

Here is my code:

TcpSe         


        
2条回答
  •  隐瞒了意图╮
    2020-12-20 08:48

    It looked like the socket got closed

    Rather than guessing, connect to the error signals of TCPServer and TCPSocket to know when errors occur, or when a client disconnects.

    The problem you have is the while(1) loop. Qt is an event-driven framework, so having code in an infinite loop on the main thread is going to prevent events being delivered.

    Instead of the infinite loop, connect to QTcpSocket::readyRead signal and handle the data when the connected slot is called.

    Qt demonstrates this with the Fortune Server and Fortune Client example code.

    If you're using C++ 11, you can use a connection to a lambda function to handle the readyRead, like this

    void TcpServer::newConnection()
    {
        ...
    
        QTcpSocket *m_TcpHttpClient = server->nextPendingConnection();
        connect(m_TcpHttpClient, &QTcpSocket::readyRead, [=](){
    
            // handle received data here
    
        });
    
    }
    

提交回复
热议问题