You need to implement a locking mechanism, such as a critical section or a mutex, to prevent multiple threads from simultaneously writing to the socket.
When receiving data intended for several streams, it is necessary to read only in one stream and transfer data to other streams if necessary.
In any case, you need to photograph your data so that the recipient knows where one message ends and the next begins. Either send the message length before sending the contents of the message, or by sending a unique separator between messages that will never be displayed in the messages themselves.
source share