Time for action – forwarding a new message
When a connected client sends a new chat message, the underlying socket—since it inherits QIODevice
—emits readyRead()
, and thus, our newMessage()
slot will be called.
Before we have a look at this slot, there is something important that you need to keep in mind. Even though TCP is ordered and without any duplicates, this does not mean that all the data is delivered in one big chunk. So, before processing the received data, we need to make sure that we get the entire message. Unfortunately, there is neither an easy way to detect whether all data was transmitted nor a globally usable method for such a task. Therefore, it is up to you to solve this problem, as it depends on the use case. Two common solutions, however, are to either send magic tokens to indicate the start and the end of a message, for example, single characters or XML tags, or you can send the size of the message upfront. The second solution is shown in the Qt documentation...