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);
        }
Esempio n. 2
0
        public async Task SendInitialMessages(CustomWebSocket userWebSocket, ICustomWebSocketFactory wsFactory)
        {
            WebSocket webSocket = userWebSocket.WebSocket;
            var       msg       = new CustomWebSocketMessage
            {
                MessagDateTime   = DateTime.Now,
                Text             = $"T{userWebSocket.Id} joined the chat",
                Username         = userWebSocket.Id,
                Id               = Guid.NewGuid(),
                IsInitialMessage = true,
                Status           = 0
            };

            wsFactory.AddMessage(msg);
            var websocketData = new CustomWebSocketData
            {
                Messages  = wsFactory.GetMessages(),
                UserNames = wsFactory.GetUserNames()
            };

            var jsonStr = JsonSerializer.Serialize <CustomWebSocketData>(websocketData);

            byte[] bytes = Encoding.ASCII.GetBytes(jsonStr);
            await BroadcastToAll(bytes, userWebSocket, wsFactory);
        }
Esempio n. 3
0
        public async Task BroadcastToAll(byte[] buffer, CustomWebSocket userWebSocket, ICustomWebSocketFactory wsFactory)
        {
            var all = wsFactory.All();

            foreach (var uws in all)
            {
                await uws.WebSocket.SendAsync(new ArraySegment <byte>(buffer, 0, buffer.Length), WebSocketMessageType.Text, true, CancellationToken.None);
            }
        }
        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);
        }
Esempio n. 5
0
 public void Add(CustomWebSocket uws)
 {
     List.Add(uws);
 }
Esempio n. 6
0
 public List <CustomWebSocket> Others(CustomWebSocket client)
 {
     return(List.Where(c => c.Id != client.Id).ToList());
 }
Esempio n. 7
0
        public async Task HandleMessage(string msg, byte[] buffer, CustomWebSocket userWebSocket, ICustomWebSocketFactory wsFactory)
        {
            try
            {
                var message = JsonSerializer.Deserialize <CustomWebSocketMainMessage>(msg);
                if (message.WSType == WebSocketMessageType.Text)
                {
                    if (message.Type == "U")
                    {
                        if (wsFactory.AddUser(message.UserName))
                        {
                            var userMsg = new CustomWebSocketMessage
                            {
                                MessagDateTime   = DateTime.Now,
                                Text             = $"{message.UserName} joined the chat",
                                Username         = message.UserName,
                                Id               = Guid.NewGuid(),
                                IsInitialMessage = true,
                                Status           = 0
                            };
                            wsFactory.AddMessage(userMsg);
                        }
                        else
                        {
                            return;
                        }
                    }
                    else
                    {
                        if (message.Message.Status == 2)
                        {
                            // delete message
                            wsFactory.DeleteMessage(message.Message);
                        }
                        else if (message.Message.Status == 1)
                        {
                            wsFactory.ModifyMessage(message.Message);
                        }
                        else
                        {
                            var newMessage = new CustomWebSocketMessage
                            {
                                Id               = Guid.NewGuid(),
                                MessagDateTime   = DateTime.Now,
                                Text             = message.Message.Text,
                                Username         = message.Message.Username,
                                IsInitialMessage = false,
                                Status           = 0
                            };
                            wsFactory.AddMessage(newMessage);
                        }
                    }

                    var websocketData = new CustomWebSocketData
                    {
                        Messages  = wsFactory.GetMessages(),
                        UserNames = wsFactory.GetUserNames()
                    };

                    var    jsonStr = JsonSerializer.Serialize <CustomWebSocketData>(websocketData);
                    byte[] bytes   = Encoding.ASCII.GetBytes(jsonStr);
                    await BroadcastToAll(bytes, userWebSocket, wsFactory);
                }
            }
            catch (Exception e)
            {
                await userWebSocket.WebSocket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);
            }
        }