diff --git a/SessionCompanion/SessionCompanion/Hubs/SessionHub.cs b/SessionCompanion/SessionCompanion/Hubs/SessionHub.cs new file mode 100644 index 0000000..9d8c7d6 --- /dev/null +++ b/SessionCompanion/SessionCompanion/Hubs/SessionHub.cs @@ -0,0 +1,51 @@ +using Microsoft.AspNetCore.SignalR; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace SessionCompanion.Hubs +{ + public class SessionHub : Hub + { + private static Dictionary ConnectedCharacters = new Dictionary(); + + public SessionHub() + { + } + + public override Task OnDisconnectedAsync(Exception exception) + { + // if true then it is character, if false it is GM + if (ConnectedCharacters.ContainsKey(Context.ConnectionId)) + { + Groups.RemoveFromGroupAsync(Context.ConnectionId, "Players"); + ConnectedCharacters.Remove(Context.ConnectionId); + } + else + Groups.RemoveFromGroupAsync(Context.ConnectionId, "GameMaster"); + Clients.All.SendAsync("GoodBye", "Player has left the game"); + return base.OnDisconnectedAsync(exception); + } + + #region GameMaster + public Task GameMasterLogin() + { + Groups.AddToGroupAsync(Context.ConnectionId, "GameMaster"); + + return Clients.All.SendAsync("Welcome", "Welcome new Game Master"); + } + #endregion + + #region Player + public Task PlayerCharacterLogin(int characterId) + { + ConnectedCharacters.Add(Context.ConnectionId, characterId); + Groups.AddToGroupAsync(Context.ConnectionId, "Players"); + + return Clients.All.SendAsync("Welcome", "Welcome new Player"); + } + #endregion + + } +} diff --git a/SessionCompanion/SessionCompanion/Startup.cs b/SessionCompanion/SessionCompanion/Startup.cs index ac583c8..da72a46 100644 --- a/SessionCompanion/SessionCompanion/Startup.cs +++ b/SessionCompanion/SessionCompanion/Startup.cs @@ -1,5 +1,6 @@ using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http.Connections; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.SpaServices.AngularCli; using Microsoft.EntityFrameworkCore; @@ -8,6 +9,7 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using SessionCompanion.Configurations; using SessionCompanion.Database; +using SessionCompanion.Hubs; namespace SessionCompanion { @@ -29,7 +31,7 @@ namespace SessionCompanion options.UseSqlServer( Configuration.GetConnectionString("DefaultConnection"))); services.AddRepositories(); - + services.AddSignalR(); // In production, the Angular files will be served from this directory services.AddSpaStaticFiles(configuration => { @@ -70,6 +72,13 @@ namespace SessionCompanion endpoints.MapControllerRoute( name: "default", pattern: "{controller}/{action=Index}/{id?}"); + + endpoints.MapHub("/sessionhub", options => + { + options.Transports = + HttpTransportType.WebSockets | + HttpTransportType.LongPolling; + }); }); app.UseSpa(spa =>