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