Exemplo n.º 1
0
 private async Task SendDataToSocket <T>(string methodName, HubSocket socket, T data)
 {
     var hubData = new HubData()
     {
         Data       = data,
         MethodName = methodName,
         PromiseId  = -1
     };
     await socket.SendData(hubData);
 }
Exemplo n.º 2
0
        public async Task AddSocket(WebSocket webSocket)
        {
            using var hubSocket = new HubSocket(Guid.NewGuid(), webSocket);

            hubSocketRepository.AddOrUpdate(hubSocket.ID, hubSocket);
            hubSocket.DataReceived += DataReceived;

            DataReceived(this, new HubSocketEventArgs()
            {
                Data = JsonConvert.SerializeObject(new HubData()
                {
                    MethodName = nameof(Hub.OnConnectedAsync)
                }),
                HubSocket = hubSocket
            });

            HubData hubSocketConnected = new HubData()
            {
                Data       = hubSocket.ID,
                MethodName = "HubSocketConnected"
            };
            await hubSocket.SendData(hubSocketConnected);

            await hubSocket.ListenLoop(); // infinite loop until socket closed.

            RemoveSocket(hubSocket.ID);

            DataReceived(this, new HubSocketEventArgs()
            {
                Data = JsonConvert.SerializeObject(new HubData()
                {
                    MethodName = nameof(Hub.OnDisconnectedAsync)
                }),
                HubSocket = hubSocket
            });
        }
Exemplo n.º 3
0
        public async void DataReceived(object sender, EventArgs e)
        {
            if (!(e is HubSocketEventArgs hubSocketEventArgs))
            {
                return;
            }

            try
            {
                foreach (var hubType in hubTypes)
                {
                    Hub hub = serviceProvider.GetRequiredService(hubType) as Hub;
                    hub.Clients = serviceProvider.GetRequiredService <HubSocketClients>();
                    hub.Context = new HubSocketContext(hubSocketEventArgs.HubSocket);

                    HubData requestHubData = JsonConvert.DeserializeObject <HubData>(hubSocketEventArgs.Data);

                    string methodName = requestHubData.MethodName;

                    JObject data = requestHubData.Data as JObject;

                    var method = hub.GetType().GetMethod(methodName,
                                                         BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);

                    if (method != null)
                    {
                        try
                        {
                            var           methodParameters = method.GetParameters();
                            List <object> targetParams     = null;

                            if (methodParameters.Any())
                            {
                                targetParams = new List <object>();
                                var jProperties = data?.Properties() ?? Enumerable.Empty <JProperty>();

                                foreach (var param in methodParameters)
                                {
                                    var jProp = jProperties.SingleOrDefault(x => x.Name == param.Name);
                                    if (jProp != null)
                                    {
                                        targetParams.Add(jProp.ToObject(param.ParameterType));
                                    }
                                }

                                if (methodParameters.Any() && methodParameters.Count() != targetParams.Count())
                                {
                                    throw new Exception($"Parameter mismatch. Method '{method.Name}' expects params: [" +
                                                        $"{string.Join(",", methodParameters.Select(x => $"{x.ParameterType.Name} {x.Name}"))}], but got [" +
                                                        string.Join(",", jProperties.Select(x => $"{x.Type} {x.Name}")) + "]");
                                }
                            }

                            var    invokeResult = method.Invoke(hub, targetParams?.ToArray());
                            object response     = null;

                            if (invokeResult is Task task)
                            {
                                await task.ConfigureAwait(false);

                                var resultProperty = task.GetType().GetProperty("Result");
                                response = resultProperty.GetValue(task);
                            }
                            else if (invokeResult != null)
                            {
                                response = invokeResult;
                            }

                            if (response != null)
                            {
                                HubData immediateResponse = new HubData()
                                {
                                    Data       = response,
                                    MethodName = null,
                                    PromiseId  = requestHubData.PromiseId
                                };

                                await hubSocketEventArgs.HubSocket.SendData(immediateResponse);
                            }
                        }
                        catch (Exception ex)
                        {
                            await hub.Clients.SendToClient("Error", hub.Context.ConnectionId, ex);
                        }
                    }
                }
            }
            catch
            {
                //log ex here
                throw;
                //await SendAll(ex);
            }
        }