Skip to content

Multiple clients and send messages to all clients #5

@DowranRowshenow

Description

@DowranRowshenow

By doing as strangerattractor said, in this issue Add Function to send messages to clients, the server can send a message to the client. But this will only send to the last connected client. As a rough solution, we can do it like this:

  1. Add new List<TcpClient> variable to the WebSocketServer class like this:

     private List<TcpClient> connectedTcpClients;
    
  2. Also add this line to the ListenForTcpConnection() function like this:

     connectedTcpClient = tcpListener.AcceptTcpClient();
     connectedTcpClients.Add(connectedTcpClient);
    
  3. Change the SendMessageToClient() function in the Add Function to send messages to clients to this:

     public virtual void SendMessageToClient(string msg)
     {
         foreach (var client in connectedTcpClients)
         {
             NetworkStream stream = client.GetStream();
             Queue<string> que = new Queue<string>(msg.SplitInGroups(125));
             int len = que.Count;
    
             while (que.Count > 0)
             {
                 var header = GetHeader(
                     que.Count > 1 ? false : true,
                     que.Count == len ? false : true
                 );
    
                 byte[] list = Encoding.UTF8.GetBytes(que.Dequeue());
                 header = (header << 7) + list.Length;
                 stream.Write(IntToByteArray((ushort)header), 0, 2);
                 stream.Write(list, 0, list.Length);
             }   
         }
     }
    

This should work with multiple clients.

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions