public void UpdateCustomWebSocket(CustomWebSocket customWebSocket)
 {
     lock (_lock)
     {
         _sockets.AddOrUpdate(customWebSocket.UserName, customWebSocket, (key, oldValue) => customWebSocket);
     }
 }
Exemplo n.º 2
0
        public async Task Invoke(HttpContext context, ICustomWebSocketFactory wsFactory, ICustomWebSocketMessageHandler wsmHandler)
        {
            if (context.Request.Path == "/ws")
            {
                if (context.WebSockets.IsWebSocketRequest)
                {
                    string username = context.Request.Query["u"];
                    if (!string.IsNullOrEmpty(username))
                    {
                        WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();

                        CustomWebSocket userWebSocket = new CustomWebSocket()
                        {
                            WebSocket = webSocket,
                            Username  = username
                        };
                        wsFactory.Add(userWebSocket);
                        await wsmHandler.SendInitialMessages(userWebSocket);
                        await Listen(context, userWebSocket, wsFactory, wsmHandler);
                    }
                }
                else
                {
                    context.Response.StatusCode = 400;
                }
            }
            await _next(context);
        }
        public async Task Invoke(HttpContext context, ICustomWebSocketFactory wsFactory, ICustomWebSocketMessageHandler wsmHandler)
        {
            if (context.Request.Path == "/ws")
            {
                if (context.WebSockets.IsWebSocketRequest)
                {
                    string groupId      = context.Request.Query["g"];
                    string friendlyName = context.Request.Query["f"];
                    string userId       = context.Request.Query["u"];
                    if (!string.IsNullOrEmpty(groupId))
                    {
                        var webSocket = await context.WebSockets.AcceptWebSocketAsync();

                        var userWebSocket = new CustomWebSocket()
                        {
                            WebSocket    = webSocket,
                            GroupId      = Guid.Parse(groupId),
                            FriendlyName = friendlyName,
                            UserId       = userId,
                        };
                        wsFactory.Add(userWebSocket);
                        _logger.Log(LogLevel.Information, new EventId((int)LogEventId.User), $"User {userId} joined group {groupId}");
                        await wsmHandler.SendInitialMessageAsync(userWebSocket, wsFactory);
                        await ListenAsync(context, userWebSocket, wsFactory, wsmHandler);
                    }
                }
                else
                {
                    context.Response.StatusCode = 400;
                }
            }
            await _nextAsync(context);
        }
        public void AddSocket(WebSocket socket, string userName)
        {
            var customWebSocket = new CustomWebSocket
            {
                UserName  = userName,
                WebSocket = socket
            };

            _sockets.AddOrUpdate(userName, customWebSocket, (key, oldValue) => customWebSocket);
        }
Exemplo n.º 5
0
        private async Task Listen(HttpContext context, CustomWebSocket userWebSocket, ICustomWebSocketFactory wsFactory, ICustomWebSocketMessageHandler wsmHandler)
        {
            WebSocket webSocket           = userWebSocket.WebSocket;
            var       buffer              = new byte[1024 * 4];
            WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);

            while (!result.CloseStatus.HasValue)
            {
                await wsmHandler.HandlerMessage(result, buffer, userWebSocket, wsFactory);

                buffer = new byte[1024 * 4];
                result = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);
            }
            wsFactory.Remove(userWebSocket.Username);
            await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
        }
 /// <summary>
 /// 行情
 /// </summary>
 /// <param name="socket"></param>
 /// <param name="customSocket"></param>
 /// <param name="messageEntity"></param>
 /// <returns></returns>
 public async Task Quote(WebSocket socket, CustomWebSocket customSocket, MessageEntity messageEntity)
 {
     // CacheService.OnConnect((sub) =>
     //{
     //    sub.Subscribe("tick_us", async (channel, message) =>
     //   {
     //       var a = message.ToString().Split('|');
     //       var SecurityCode = a[0];
     //       var price = Convert.ToInt32(a[1]);
     //       var tradePrice = price;
     //       var tradeSize = Convert.ToInt32(a[2]);
     //       var utcTick = Convert.ToInt64(a[3]);
     //       var flagUp = a[4];
     //       var type = a[5];//2:美股
     //       var Ttype = a[6];//交易类型:0
     //       var msg = string.Format("{0} | {1} |  {2}  | {3}   \r\n", Utils.ConvertDateTime(utcTick).ToString("HH:mm:ss"),
     //                   ConverPrice(tradePrice),
     //                   flagUp,
     //                   String.Format("{0:D4}", tradeSize)
     //                  );
     //       msg = $"{msg} |{SecurityCode}";
     //       messageEntity.D = msg;
     //       await _webSocketHandler.SendMessageAsync(socket, messageEntity);
     //   });
     //});
     ///模拟行情
     while (true)
     {
         Thread.Sleep(100);
         var securityCode = "AAPL";
         var msg          = string.Format("{0} | {1} |  {2}  | {3}   \r\n", DateTime.Now.ToString("HH:mm:ss"),
                                          123,
                                          0,
                                          String.Format("{0:D4}", 5555)
                                          );
         msg             = $"{msg} |{securityCode}";
         messageEntity.D = msg;
         await _webSocketHandler.SendMessageAsync(socket, messageEntity);
     }
     // _webSocketHandler.UpdateCustomWebSocket(customSocket);
 }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="socket"></param>
        /// <param name="customSocket"></param>
        /// <param name="messageEntity"></param>
        /// <returns></returns>
        public async Task Login(WebSocket socket, CustomWebSocket customSocket, MessageEntity messageEntity)
        {
            if (string.IsNullOrEmpty(messageEntity.D))
            {
                messageEntity.D = "请输入参数";
                await _webSocketHandler.SendMessageAsync(socket, messageEntity);

                return;
            }
            try
            {
                //var tradeLoginRQ = JsonConvert.DeserializeObject<LoginRQ>(messageEntity.D);
                messageEntity.D = "登录成功";
                await _webSocketHandler.SendMessageAsync(socket, messageEntity);

                return;
            }
            catch
            {
            }
        }
        private async Task ListenAsync(HttpContext context, CustomWebSocket userWebSocket, ICustomWebSocketFactory wsFactory, ICustomWebSocketMessageHandler wsmHandler)
        {
            var webSocket = userWebSocket.WebSocket;

            byte[] buffer  = new byte[1024 * 16];
            var    message = new List <byte>();
            WebSocketReceiveResult response;

            do
            {
                do
                {
                    response = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);

                    message.AddRange(new ArraySegment <byte>(buffer, 0, response.Count));
                } while (!response.EndOfMessage);
                await wsmHandler.HandleMessageAsync(response, message, userWebSocket, wsFactory);
            } while (!response.CloseStatus.HasValue);

            await wsmHandler.SendDisconnectMessageAsync(userWebSocket, wsFactory);

            wsFactory.Remove(userWebSocket.GroupId, userWebSocket.UserId);
            await webSocket.CloseAsync(response.CloseStatus.Value, response.CloseStatusDescription, CancellationToken.None);
        }
Exemplo n.º 9
0
 public void UpdateCustomWebSocket(CustomWebSocket customWebSocket)
 {
     WebSocketConnectionManager.UpdateCustomWebSocket(customWebSocket);
 }