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); }
public void DeleteMessage(CustomWebSocketMessage msg) { var foundIndex = Messages.FindIndex(ind => ind.Id == msg.Id); if (foundIndex > -1) { Messages[foundIndex].Text = "This message was deleted."; Messages[foundIndex].Status = 2; } }
public void ModifyMessage(CustomWebSocketMessage msg) { var foundIndex = Messages.FindIndex(ind => ind.Id == msg.Id); if (foundIndex > -1) { msg.Text = msg.Text + "( edited )"; msg.Status = 1; Messages[foundIndex] = msg; } }
public void AddMessage(CustomWebSocketMessage msg) { Messages.Add(msg); }
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); } }