예제 #1
0
        private void _ws_OnMessage(object sender, MessageEventArgs e)
        {
            var m = new Message().ToObject(e.Data);

            if (m == null)
            {
                var r = JsonConvert.DeserializeObject <Result>(e.Data);
                if (r?.Namespace == "result")
                {
                    ResultReceived?.Invoke(this, r);
                }
                //else //DEBUG, checking for messages we don't know about
                //Console.WriteLine(e.Data);
                return;
            }

            if (m is Connect c)
            {
                if (c.Payload == RESPONSE_CODE_REQUIRED)
                {
                    ConnectReceived.Invoke(this, RESPONSE_CODE_REQUIRED);
                }
                else if (Guid.TryParse(c.Payload, out Guid g))
                {
                    ConnectReceived.Invoke(this, c.Payload);
                }
                return;
            }
            MessageReceived?.Invoke(this, m);

            Type t = Assembly.GetExecutingAssembly().GetTypes().FirstOrDefault(x => x == m.GetType() && x.IsSubclassOf(typeof(Message)));

            if (t != null)
            {
                dynamic nm    = Convert.ChangeType(m, t);
                var     field = this.GetType().GetField($"{t.Name}Received", BindingFlags.Instance | BindingFlags.NonPublic);
                var     em    = field?.GetValue(this);
                em?.GetType().GetMethod("Invoke").Invoke(em, new[] { this, nm.Payload });
            }
            else
            {
                OnError?.Invoke(this, $"Invalid Message Received: {e.Data}");
            }
        }