Time for action – sending text messages
What is left is now is to describe how to send a chat massage. On hitting return 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:
QString message = m_user + ": " + ui->text->text(); m_socket->write(message.toLocal8Bit()); ui->text->clear();
If so, a message is composed that contains the self-given username, a colon, and the text of the line edit. To send this string to the peer, the QTcpSocket::write()
server is called. Since write()
only accepts const char*
or QByteArray
, we use QString::toLocal8Bit()
to get QByteArray
that we can send over the socket.
That's all. It's like writing and reading from a file. For the complete example, have a look at the sources bundled with this book and run the server and several clients.
Have a go hero – extending the chat with a user list
This example has shown us how to send a simple...