Skip to content

Commit

Permalink
Unity server is now done
Browse files Browse the repository at this point in the history
  • Loading branch information
devedse committed Sep 29, 2023
1 parent 10a813d commit ca7a76a
Showing 1 changed file with 37 additions and 3 deletions.
40 changes: 37 additions & 3 deletions UnityGameServer/UnityGameServer/Hubs/UltraHub.cs
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);
}
}
}

0 comments on commit ca7a76a

Please sign in to comment.