<Solved> TCP client read wrong data from server
Unsolved
General and Desktop
-
Hi, i created tcp server and client. Server send data to clients, but client read wrong data. Please help me.
This slot conneted with signal readyRead() at a client.
void Client::readSocketData() { QDataStream in(m_socket); while(true) { if (m_nextBlockSize == 0) { if (m_socket->bytesAvailable() < sizeof(quint16(0))) return; in >> m_nextBlockSize; qDebug() << m_nextBlockSize; } if (m_socket->bytesAvailable() < m_nextBlockSize) { return; } QString text; in >> text; qDebug() << text; m_nextBlockSize = 0; } }
client class for server
ClientConnection::ClientConnection(int socketDescriptor, QObject *parent) : QThread(parent), m_socketDescriptor(socketDescriptor) { } void ClientConnection::writeData(const QString& text) { QByteArray rawData; QDataStream data(&rawData, QIODevice::ReadWrite); data << quint16(0) << text; data.device()->seek(0); data << quint16(rawData.size() - sizeof(quint16)); m_socket->write(rawData); m_socket->waitForBytesWritten(); } void ClientConnection::run() { qDebug() << "New connection"; m_socket = new QTcpSocket(); m_socket->setSocketDescriptor(m_socketDescriptor); }
Class Server
MyServer::MyServer(QObject *parent) : QTcpServer(parent) { if(!this->listen(QHostAddress::Any, 1234)) { qDebug() << "Could not start server"; } else { qDebug() << "Listening..."; } } void MyServer::sendText(const QString &text) { for(int i = 0; i < m_connections.size(); ++i) { m_connections.at(i)->writeData(text); } } void MyServer::incomingConnection(int handle) { ClientConnection *client = new ClientConnection(handle); client->start(); m_connections.push_back(client); }
-
Hi,
What do you mean by wrong data ? What do you expect ? What do you get ?
-
Nice you found out and thanks for sharing :)
There's no need to modify the title anymore to mark the thread as solved, you can use the "Topic Tool" button for that :)