protected void HandleConfiguration(byte[] data) { if (ConfigurationMessage.TryDecode(data, _encoding, out ConfigurationMessage msg)) { _eventManager = new ControllersEventManager(msg, _encoding); } else { throw new InvalidDataException("Invalid configuration message."); } }
/// <summary> /// Sends a configuration message which sets binding between ids and types of event. /// </summary> public async Task <bool> SendConfigurationAsync(WebSocket socket, ConfigurationMessage msg) { try { IsEventChannel = false; await socket.SendAsync(new ArraySegment <byte>(new ChangeStateMessage(MessageManagerState.Configuration).Encode(_encoding)), WebSocketMessageType.Binary, true, _src.Token); await socket.SendAsync(new ArraySegment <byte>(msg.Encode(_encoding)), WebSocketMessageType.Binary, true, _src.Token); } catch (Exception) { return(false); } return(true); }
/// <summary> /// Decodes the message and finds Type instances by their name in the data. /// </summary> public static bool TryDecode(byte[] data, Encoding encoding, out ConfigurationMessage msg) { msg = new ConfigurationMessage(); if (data == null || data.Length < 3) { return(false); } int countOfControllers = data[2]; int skip = countOfControllers == 0 ? 1 : 2; byte[][] records = data.Split(0, skip + countOfControllers); // Go through all records and find their types. for (int i = skip; i < skip + countOfControllers; i++) { byte id = records[i][0]; string nameOfClass = encoding.GetString(records[i], 1, records[i].Length - 1); try { var classType = Type.GetType(nameOfClass); if (classType.IsSubclassOf(typeof(ControllerEvent))) { msg.AddBinding(id, classType); } else { return(false); } } catch (Exception) { return(false); } } return(true); }
/// <summary> /// The constructor. Binding between ids and events are obtained from <see cref="ConfigurationMessage"/>. /// </summary> public ControllersEventManager(ConfigurationMessage msg, Encoding encoding) { Args = msg.Args; _encoding = encoding; }