SHARE
TWEET

Untitled

a guest Jun 20th, 2019 64 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class WebSocketHandler : IWebSocketRequestHandler
  2. {
  3.     private Dictionary<string,WebSocket> _webSockets = new Dictionary<string, WebSocket>();
  4.     public event MessageRecivedHandler MessageRecived;
  5.     private IdHelper _portMappings;
  6.  
  7.     public WebSocketHandler(IdHelper portMappings)
  8.     {
  9.         _portMappings = portMappings;
  10.     }
  11.  
  12.  
  13.  
  14.     public void Connected(WebSocket socket)
  15.     {
  16.         var guid = Guid.NewGuid().ToString();
  17.         _webSockets.Add(guid, socket);
  18.  
  19.  
  20.         socket.DataReceived += (webSocket, frame) => MessageRecived?.Invoke(_webSockets.First(x => x.Value == webSocket).Key,webSocket, frame);
  21.         socket.ConnectionClosed += (webSocket) =>
  22.         {
  23.             var connection = _webSockets.First(s => s.Value == webSocket);
  24.             _webSockets.Remove(connection.Key);
  25.         };
  26.  
  27.         if (_portMappings.IsBindingPosible())
  28.         {
  29.             _portMappings.Bind(guid);
  30.  
  31.             var message = new ServerMessage()
  32.             {
  33.                 ClientID = guid,
  34.                 Command = "Init",
  35.                 Value = _portMappings.CheckBinding(guid).ToString()
  36.             };
  37.             SendMessage(guid, message);
  38.         }
  39.         else
  40.         {
  41.             var message = new ServerMessage()
  42.             {
  43.                 ClientID = guid,
  44.                 Command = "Init",
  45.                 Value = "Max Number Of Clients Reached. Please close connection"
  46.             };
  47.             SendMessage(guid, message);
  48.         }
  49.  
  50.  
  51.     }
  52.  
  53.     public bool WillAcceptRequest(string uri, string protocol)
  54.     {
  55.         return true;
  56.     }
  57.  
  58.     public async Task BroadcastMessage(string message)
  59.     {
  60.         await ThreadPool.RunAsync((workItem) => _webSockets?.AsParallel().ForAll(webSocket => webSocket.Value.Send(message)));
  61.     }
  62.  
  63.     public async Task SendMessage(string guid, ServerMessage message)
  64.     {
  65.         await ThreadPool.RunAsync((workItem) => _webSockets?.First(x => x.Key == guid).Value.Send(JsonConvert.SerializeObject(message)));
  66.     }
  67.     public delegate void MessageRecivedHandler(string guid, WebSocket socket, string message);
  68. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top