Time for action – Sending text messages

What is left now is to describe how to send a chat message. On hitting return button inside the line edit, a local slot will be called that checks whether there is actual text to send and whether m_socket is still connected. If everything is ready, we construct a message that contains the self-given username, a colon, and the text of the line edit:

QString message = QStringLiteral("%1: %2")
                  .arg(m_user).arg(ui->text->text());

Then, we encode and send the message, just like we did on the server side:

QByteArray messageArray = message.toUtf8();
messageArray.append(23);
m_socket->write(messageArray);

That's all. It's like writing and reading from a file. For the complete example, take a look at the sources ...

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.