unity-websocket-server
unity-websocket-server copied to clipboard
Multiple clients and send messages to all clients
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:
-
Add new
List<TcpClient>
variable to theWebSocketServer
class like this:private List<TcpClient> connectedTcpClients;
-
Also add this line to the
ListenForTcpConnection()
function like this:connectedTcpClient = tcpListener.AcceptTcpClient(); connectedTcpClients.Add(connectedTcpClient);
-
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.
Updated to also remove clients from the List when they are no longer connected...
public virtual void SendMessageToClient(string msg)
{
foreach (var client in connectedTcpClients)
{
if (!client.Connected)
{
connectedTcpClients.Remove(client);
}
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);
}
}
}
Change the following line:
private List<TcpClient> connectedTcpClients;
to this:
private List<TcpClient> connectedTcpClients = new();