using System; using IotWeb.Common.Http; using System.Threading.Tasks; using System.Collections.Generic; using System.Diagnostics; using Nibriboard.Client.Messages; namespace Nibriboard.Client { /// /// Manages a group of s. /// public class NibriClientManager : IWebSocketRequestHandler { private ClientSettings clientSettings; public List Clients = new List(); /// /// The number of clients currently connected to this Nibriboard. /// public int ClientCount { get { return Clients.Count; } } public NibriClientManager(ClientSettings inClientSettings) { clientSettings = inClientSettings; } /// /// Whether we will accept a given new WebSocket connection or not. /// /// The uri the user connected to. /// The protocol the user is connecting with. /// Whether we want to accept the WebSocket connection attempt or not. public bool WillAcceptRequest(string uri, string protocol) { Log.WriteLine("[Nibriboard/Websocket] Accepting new {0} connection.", protocol); return clientSettings.WebsocketProtocol == protocol; } /// /// Handles WebSocket clients when they first connect, wrapping them in /// a instance and adding them to /// the client list. /// /// New socket. public void Connected(WebSocket newSocket) { NibriClient client = new NibriClient(this, newSocket); client.Disconnected += handleDisconnection; // Clean up when the client disconnects Clients.Add(client); } /// /// Sends a message to all the connected clients, except the one who's sending it. /// /// The client sending the message. /// The message that is to bee sent. public void Broadcast(NibriClient sendingClient, Message message) { foreach(NibriClient client in Clients) { // Don't send the message to the sender if (client == sendingClient) continue; client.Send(message); } } /// /// Clean up after a client disconnects from the server. /// /// The client that has disconnected. private void handleDisconnection(NibriClient disconnectedClient) { Clients.Remove(disconnectedClient); } } }