From ca7a76aff3f82d258464563e8262dafb4f43238b Mon Sep 17 00:00:00 2001 From: Devedse Date: Sat, 30 Sep 2023 01:19:43 +0200 Subject: [PATCH] Unity server is now done --- .../UnityGameServer/Hubs/UltraHub.cs | 40 +++++++++++++++++-- 1 file changed, 37 insertions(+), 3 deletions(-) diff --git a/UnityGameServer/UnityGameServer/Hubs/UltraHub.cs b/UnityGameServer/UnityGameServer/Hubs/UltraHub.cs index 2469bf0..612c6d4 100644 --- a/UnityGameServer/UnityGameServer/Hubs/UltraHub.cs +++ b/UnityGameServer/UnityGameServer/Hubs/UltraHub.cs @@ -1,13 +1,47 @@ using Microsoft.AspNetCore.SignalR; +using System.Collections.Concurrent; namespace UnityGameServer.Hubs { public class UltraHub : Hub { - public async Task SendMessage(string user, string message) + // Use ConcurrentBag to ensure thread safety when adding or checking room names + private static readonly ConcurrentBag roomNames = new ConcurrentBag(); + + public string CreateUniqueRoomName() + { + string roomName; + do + { + roomName = CreateRandomRoomName(); + } while (roomNames.Contains(roomName)); + + roomNames.Add(roomName); + return roomName; + } + + private string CreateRandomRoomName() + { + var random = new Random(); + const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + return new string(Enumerable.Repeat(chars, 4) + .Select(s => s[random.Next(s.Length)]).ToArray()); + } + + public Task Server_CreateRoom() + { + string roomName = CreateUniqueRoomName(); + return Groups.AddToGroupAsync(Context.ConnectionId, roomName); + } + + public Task Client_JoinRoom(string roomName) + { + return Groups.AddToGroupAsync(Context.ConnectionId, roomName); + } + + public Task Client_SendButtonPress(int button) { - Console.WriteLine($"Received a message from: {user} with the message: {message}"); - await Clients.All.SendAsync("ReceiveMessage", user, message); + return Clients.Others.SendAsync("Server_ReceiveButtonPress", button); } } }