QTcpSocket received data type
Solved
General and Desktop
-
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); label->setText(utf8str); }else if(type == "image"){ QPixmap pixmap; pixmap.loadFromData(BA); label->setPixmap(pixmap); } }
-
Distinguishing the data type is not your problem here.
Have a look at this example, especially theChatClient::sendMessage
andChatClient::onReadyRead
methods. -
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