Time for action – Receiving text messages

In the constructor, we have connected the socket's readyRead() signal to a local slot. So, whenever the server sends a message through QTcpSocket::write(), we read the data and decode it:

m_receivedData.append(m_socket->readAll());
while(true) {
    int endIndex = m_receivedData.indexOf(23);
    if (endIndex < 0) {
        break;
    }
    QString message = QString::fromUtf8(m_receivedData.left(endIndex));
    m_receivedData.remove(0, endIndex + 1);
    newMessage(message);
}

This code is very similar to the readyRead() slot of the server. It's even simpler because we only have one socket and one data buffer, so m_receivedData is a single QByteArray. The newMessage() implementation in the client is also much simpler than in the ...

Get Game Programming using Qt 5 Beginner's Guide - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.