How to get formatted message from TcpSocket
-
I have message which send to TcpSocket with format: 0x02 + msg + 0x03
start: 0x02
end: 0x03
How I can got msg from this.void TcpAcServer::newConnection() { QTcpSocket *newClient = server->nextPendingConnection(); clients << newClient; connect(newClient, SIGNAL(readyRead()), this, SLOT(receivedData())); connect(newClient, SIGNAL(disconnected()), this, SLOT(disconnected())); } void TcpAcServer::receivedData() { QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender()); if (socket == 0) { // Neu khong xac dinh duoc nguon phat, chung ta se dung xu ly return; } // TODO: how to extract msg ???
-
@SilentWolf said in How to get formatted message from TcpSocket:
I have message which send to TcpSocket with format: char(2) + msg + char(3)
You can't until you define how you know the length of the msg segment, or how it is terminated. Or is the
char(3)
a particular pattern which is recognisable? -
@JonB said in How to get formatted message from TcpSocket:
rticular patter
Yes. char(3) is pattern which recognize end of msg segment.
-
@SilentWolf
Then you need to keep accumulating bytes into a buffer (class variable) till you find find thechar(3)
pattern in the buffer. Then your message is to the left of that, skipping the first 2 characters. Remove that message with its leading & trailing bytes from the buffer and continue for next message.Of course if you service multiple connected clients you will need to recognise which one and have separate buffers for each client.
QDataStream has Read Transactions, but I'm not sure your protocol lends itself to using that.
-
Hi,
Are both ends written with Qt ?
-
-
Thank all,
I fixed my problemQHash<QTcpSocket*, QByteArray*> clients; void TcpAcServer::receivedData() { QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender()); if (socket == 0) { return; } QByteArray *buffer = clients.value(socket); while (socket->bytesAvailable() > 0) { buffer->append(socket->readAll()); if (buffer->contains(0x03)){ QByteArray data = buffer->mid(0, buffer->size()); broadcastMessage(false, data); buffer->remove(0, buffer->size()); break; } } }