-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
37 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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<string> roomNames = new ConcurrentBag<string>(); | ||
|
||
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); | ||
} | ||
} | ||
} |