private async void _webSockets_MessageRecived(string guid, WebSocket socket, string message) { try { var recivedData = DeserializeObject<ServerMessage>(message); await ProcessMessage(guid, recivedData); } catch (JsonReaderException e) { var messageErr = new ServerMessage() { ClientID = guid, Command = "Error", Value = "Wrong message's format" }; _webSockets.SendMessage(guid, messageErr); } }
public void Connected(WebSocket socket) { var guid = Guid.NewGuid().ToString(); _webSockets.Add(guid, socket); socket.DataReceived += (webSocket, frame) => MessageRecived?.Invoke(_webSockets.First(x => x.Value == webSocket).Key,webSocket, frame); socket.ConnectionClosed += (webSocket) => { var connection = _webSockets.First(s => s.Value == webSocket); _webSockets.Remove(connection.Key); }; if (_portMappings.IsBindingPosible()) { _portMappings.Bind(guid); var message = new ServerMessage() { ClientID = guid, Command = "Init", Value = _portMappings.CheckBinding(guid).ToString() }; SendMessage(guid, message); } else { var message = new ServerMessage() { ClientID = guid, Command = "Init", Value = "Max Number Of Clients Reached. Please close connection" }; SendMessage(guid, message); } }
public async Task SendMessage(string guid, ServerMessage message) { await ThreadPool.RunAsync((workItem) => _webSockets?.First(x => x.Key == guid).Value.Send(JsonConvert.SerializeObject(message))); }
private async Task ProcessMessage(string guid, ServerMessage message) { if (_portMapping.IsBinded(guid)) { if (message.Command != null && message.Value != null) { switch (message.Command) { case "RegisterClient": { var command = new ValueSet { { "Command", message.Command }, { "Value", message.Value } }; var responseStatus = await _appServiceConnection.SendMessageAsync(command); break; } case "ValueReq": { var response = new ServerMessage() { ClientID = guid, Command = "Value", Value = _currentValue }; await _webSockets.SendMessage(guid, response); break; } case "ValueAck": { var command = new ValueSet { { "Command", message.Command }, { "Value", message.Value } }; var responseStatus = await _appServiceConnection.SendMessageAsync(command); break; } case "Disc": { var command = new ValueSet { { "Command", message.Command }, { "Value", message.Value } }; var responseStatus = await _appServiceConnection.SendMessageAsync(command); _portMapping.UnBind(guid); break; } default: { var messageErr = new ServerMessage() { ClientID = guid, Command = "Error", Value = "Unknown command" }; _webSockets.SendMessage(guid, messageErr); break; } } } else { var messageErr = new ServerMessage() { ClientID = guid, Command = "Error", Value = "Wrong message's format" }; _webSockets.SendMessage(guid, messageErr); } } else { var messageErr = new ServerMessage() { ClientID = guid, Command = "Error", Value = "Please close connection" }; _webSockets.SendMessage(guid, messageErr); } }