Important: Please read the Qt Code of Conduct -

QTcpSocket received data type

  • How to distinguish received data type of QTcpSocket ?

        tcpServer = new QTcpServer(this);
        tcpServer->listen(QHostAddress::Any, 9999);
        connect(tcpServer, SIGNAL(newConnection()), this, SLOT(newConnect()));
    void MainWindow::newConnect()
        tcpSocket = tcpServer->nextPendingConnection();
        connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(readMessage()));
    void MainWindow::readMessage()
        qint64 len = tcpSocket->bytesAvailable();
        QByteArray BA = tcpSocket->read(len);
        //QString type = ?
        QLabel *label = new QLabel;
        if(type == "text"){
            QTextCodec *utf8codec = QTextCodec::codecForName("UTF-8");    
            QString utf8str = utf8codec->toUnicode(BA);
        }else if(type == "image"){
            QPixmap pixmap;

  • @sonichy

    As you have to do with any other comm lib. You need know the format to be received respectively the device has to tell you what to expect.

  • Distinguishing the data type is not your problem here.
    Have a look at this example, especially the ChatClient::sendMessage and ChatClient::onReadyRead methods.

  • @VRonin Thanks, you use JSON to set type and content !

    QJsonObject message;
    message["type"] = QStringLiteral("message");
    message["text"] = text;

  • I do but doesn't really matter, you can even write directly to the datastream clientStream << QStringLiteral("message") << text; as long as the receiver also uses the same structure to read. The key takeaway form that example is how to send and receive data to deal with cases in which partial data is received or more than 1 message is received at once

Log in to reply