Beispiel #1
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, username + new Random().Next(0, 100));
                        wsFactory.Add(userWebSocket);
                        await wsmHandler.HandleNewUserMessage(wsFactory);
                        await Listen(context, userWebSocket, wsFactory, wsmHandler);
                    }
                }
                else
                {
                    context.Response.StatusCode = 400;
                }
            }
            await _next(context);
        }
        /// <summary>
        /// 心跳类
        /// </summary>
        public async Task Invoke(string Username, ICustomWebSocketFactory wsFactory, ICustomWebSocketMessageHandler wsmHandler)
        {
            while (true)
            {
                try
                {
                    System.Threading.Thread.Sleep(1000);

                    List <CustomWebSocket> CustomWebSocketList = new List <CustomWebSocket>();
                    CustomWebSocketList = wsFactory.Others(Username);

                    foreach (CustomWebSocket item in CustomWebSocketList)
                    {
                        if (item.WebSocket.State == WebSocketState.Aborted || item.WebSocket.State == WebSocketState.Closed)
                        {
                            wsFactory.Remove(item.Username);
                            ClientWebSocket _webSocket    = new ClientWebSocket();
                            CustomWebSocket userWebSocket = new CustomWebSocket()
                            {
                                WebSocket = _webSocket,
                                Username  = item.Username,
                                UseSid    = item.UseSid,
                                Url       = item.Url
                            };
                            wsFactory.Add(userWebSocket);
                            await wsmHandler.SendInitialMessages(userWebSocket);

                            //await Listen(context, userWebSocket, wsFactory, wsmHandler);
                        }
                    }
                }
                catch (WebSocketException e)
                {
                    // 产生 10035 == WSAEWOULDBLOCK 错误,说明被阻止了,但是还是连接的
                    //if (e.NativeErrorCode.Equals(10035))
                    //{
                    //    return true;
                    //}
                    //else
                    //{
                    //    return false;
                    //}
                }
                finally
                {
                    //socket.Blocking = blockingState;    // 恢复状态
                }
            }
        }
        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.HandleMessage(result, buffer, userWebSocket, wsFactory);

                buffer = new byte[1024 * 4];
                result = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);
            }
            wsFactory.Remove(userWebSocket);
            //Log4netHelper.Info(this, "websokct关闭,移除用户为:" + userWebSocket.Username);
            await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
        }
        public async Task Invoke(HttpContext context, ICustomWebSocketFactory wsFactory, ICustomWebSocketMessageHandler wsmHandler)
        {
            if (context.Request.Path == "/ws")
            {
                if (context.Request.Headers.ContainsKey("Sec-WebSocket-Protocol"))
                {
                    context.Response.Headers.Add("Sec-WebSocket-Protocol", "protocol1");
                }
                if (context.WebSockets.IsWebSocketRequest)
                {
                    string username = context.Request.Query["u"];
                    string token    = context.Request.Query["token"];
                    //Log4netHelper.Info(this, "websokct进入,用户为:" + username);
                    if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(token) && token.Length == 36)
                    {
                        WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();

                        CustomWebSocket userWebSocket = new CustomWebSocket()
                        {
                            WebSocket = webSocket,
                            Username  = username,
                            token     = token
                        };
                        wsFactory.Add(userWebSocket);
                        wsFactory.RemoveInvalid();
                        await wsmHandler.SendInitialMessages(userWebSocket);
                        await Listen(context, userWebSocket, wsFactory, wsmHandler);
                    }
                }
                else
                {
                    context.Response.StatusCode = 400;
                    //Log4netHelper.Info(this, "不是websocket请求!");
                }
            }
            else
            {
                await _next(context);
            }
        }
Beispiel #5
0
        public async Task Invoke(HttpContext context, ICustomWebSocketFactory wsFactory, ICustomWebSocketMessageHandler wsmHandler)
        {
            if (context.Request.Path == "/GetMarket")
            {
                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);
        }
        private async Task Listen(HttpContext context, CustomWebSocket userWebSocket, ICustomWebSocketFactory wsFactory, ICustomWebSocketMessageHandler wsmHandler)
        {
            //await wsmHandler.SendInitialMessages(userWebSocket);

            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.HandleMessage(result, buffer, userWebSocket, wsFactory);
                //await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None);
                await wsmHandler.SendInitialMessages(userWebSocket);

                result = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);
            }

            wsFactory.Remove(userWebSocket.SocketId);
            await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
        }
        public async Task Invoke(HttpContext context, ICustomWebSocketFactory wsFactory, ICustomWebSocketMessageHandler wsmHandler)
        {
            if (!context.WebSockets.IsWebSocketRequest)
            {
                await next(context);

                return;
            }

            if (context.Request.Path == "/ws")
            {
                //var auth = context.Request.Headers.Where(header => header.Key == "Authorization").FirstOrDefault();
                //if (auth.Key == null || string.IsNullOrWhiteSpace(auth.Value))
                //{
                //    context.Response.StatusCode = 401;
                //    return;
                //}

                WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();

                CustomWebSocket userWebSocket = new CustomWebSocket()
                {
                    WebSocket = webSocket,
                    SocketId  = new Random().Next(100000).ToString()
                };
                wsFactory.Add(userWebSocket);
                await Listen(context, userWebSocket, wsFactory, wsmHandler);
            }
            else
            {
                context.Response.StatusCode = 400;
                return;
            }
        }
        private async Task Listen(HttpContext context, CustomWebSocket userWebSocket, ICustomWebSocketFactory wsFactory, ICustomWebSocketMessageHandler wsmHandler)
        {
            WebSocket webSocket = userWebSocket.WebSocket;

            using IMemoryOwner <byte> memory = MemoryPool <byte> .Shared.Rent(1024 * 4);

            var buffer = new byte[1024 * 4];
            WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);

            while (!result.CloseStatus.HasValue)
            {
                string msg = Encoding.UTF8.GetString(buffer, 0, result.Count);
                await wsmHandler.HandleMessage(msg, buffer, userWebSocket, wsFactory);

                buffer = new byte[1024 * 4];
                result = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);
            }
            wsFactory.Remove(userWebSocket.Id);
            await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
        }
        public async Task Invoke(HttpContext context, ICustomWebSocketFactory wsFactory, ICustomWebSocketMessageHandler wsmHandler)
        {
            if (context.Request.Path == "/ws")
            {
                if (context.WebSockets.IsWebSocketRequest)
                {
                    string client = context.Request.Query["u"];
                    if (!string.IsNullOrEmpty(client) && wsFactory.IsClientUnique(client))
                    {
                        WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();

                        CustomWebSocket userWebSocket = new CustomWebSocket()
                        {
                            WebSocket = webSocket,
                            Id        = client
                        };
                        wsFactory.Add(userWebSocket);
                        await Listen(context, userWebSocket, wsFactory, wsmHandler);
                    }
                }
                else
                {
                    context.Response.StatusCode = 400;
                }
            }
            await _next(context);
        }
        /// <summary>
        /// 连接
        /// </summary>
        /// <param name="context"></param>
        /// <param name="wsFactory"></param>
        /// <param name="wsmHandler"></param>
        /// <returns></returns>
        public async Task Invoke(HttpContext context, ICustomWebSocketFactory wsFactory, ICustomWebSocketMessageHandler wsmHandler, IAutomaticPostingFactory apFactory)
        {
            if (context.Request.Path == "/MesServiceStation")
            {
                Helperlog4.Info("新连接完成" + context.Request.Path.ToString());
                if (context.WebSockets.IsWebSocketRequest)
                {
                    System.Security.Principal.WindowsIdentity currentUser = System.Security.Principal.WindowsIdentity.GetCurrent();
                    string usesid           = currentUser.User.ToString();
                    string customwebsocketS = context.Request.Query["username"];
                    //string username = usesid + "------Name";
                    if (!string.IsNullOrEmpty(customwebsocketS))
                    {
                        CustomWebSocket customwebsocket = customwebsocketS.ConvertToObject <CustomWebSocket>();
                        WebSocket       webSocket       = await context.WebSockets.AcceptWebSocketAsync();

                        List <CustomWebSocket> CustomWebSocketList = new List <CustomWebSocket>();
                        CustomWebSocketList = wsFactory.Others(customwebsocket.Username);
                        if (CustomWebSocketList.Count > 0)
                        {
                            CustomWebSocket userWebSocket1 = new CustomWebSocket();
                            userWebSocket1 = CustomWebSocketList[0];
                            wsFactory.Remove(userWebSocket1.Username);
                            CustomWebSocket userWebSocket = new CustomWebSocket()
                            {
                                WebSocket = webSocket,
                                Username  = userWebSocket1.Username,
                                UseSid    = usesid,
                                Url       = context.Request.GetDisplayUrl(),
                                UserType  = userWebSocket1.UserType
                            };
                            wsFactory.Add(userWebSocket);
                            //await Heartbeat(wsFactory, wsmHandler);
                            Helperlog4.Info("重新连接返回值" + userWebSocket.ConvertToJson());
                            await wsmHandler.SendInitialMessages(userWebSocket);
                            await Listen(context, userWebSocket, wsFactory, wsmHandler, apFactory);
                        }
                        else
                        {
                            CustomWebSocket userWebSocket = new CustomWebSocket()
                            {
                                WebSocket = webSocket,
                                Username  = customwebsocket.Username,
                                UseSid    = usesid,
                                Url       = context.Request.GetDisplayUrl(),
                                UserType  = customwebsocket.UserType
                            };
                            wsFactory.Add(userWebSocket);

                            Helperlog4.Info("新连接返回值" + userWebSocket.ConvertToJson());
                            //await Heartbeat(wsFactory, wsmHandler);
                            await wsmHandler.SendInitialMessages(userWebSocket);
                            await Listen(context, userWebSocket, wsFactory, wsmHandler, apFactory);
                        }
                    }
                }
                else
                {
                    context.Response.StatusCode = 400;
                }
            }
            await _next(context);
        }
        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);
        }
        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);
        }