From decb0e5bea87f8a7e905334a84a44eb21587e1d2 Mon Sep 17 00:00:00 2001 From: chsakell Date: Sun, 25 Sep 2016 13:52:43 +0300 Subject: [PATCH] integrate Web API and SignalR --- Controllers/ApiHubController.cs | 21 +++++++++++++++++++++ Controllers/ValuesController.cs | 7 ++++++- Hubs/Broadcaster.cs | 17 +++++++++++++++++ 3 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 Controllers/ApiHubController.cs create mode 100644 Hubs/Broadcaster.cs diff --git a/Controllers/ApiHubController.cs b/Controllers/ApiHubController.cs new file mode 100644 index 0000000..5a22ccc --- /dev/null +++ b/Controllers/ApiHubController.cs @@ -0,0 +1,21 @@ +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.SignalR; +using Microsoft.AspNetCore.SignalR.Infrastructure; +using Microsoft.AspNetCore.SignalR.Hubs; + +namespace LiveGameFeed.Controllers +{ + public abstract class ApiHubController : Controller + where T : Hub + { + private readonly IHubContext _hub; + public IHubConnectionContext Clients { get; private set; } + public IGroupManager Groups { get; private set; } + protected ApiHubController(IConnectionManager signalRConnectionManager) + { + var _hub = signalRConnectionManager.GetHubContext(); + Clients = _hub.Clients; + Groups = _hub.Groups; + } + } +} \ No newline at end of file diff --git a/Controllers/ValuesController.cs b/Controllers/ValuesController.cs index b7cf7d4..86f7655 100644 --- a/Controllers/ValuesController.cs +++ b/Controllers/ValuesController.cs @@ -3,12 +3,17 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.SignalR.Infrastructure; +using LiveGameFeed.Hubs; namespace LiveGameFeed.Controllers { [Route("api/[controller]")] - public class ValuesController : Controller + public class ValuesController : ApiHubController { + public ValuesController(IConnectionManager signalRConnectionManager) + : base(signalRConnectionManager) { } + // GET api/values [HttpGet] public IEnumerable Get() diff --git a/Hubs/Broadcaster.cs b/Hubs/Broadcaster.cs new file mode 100644 index 0000000..0963ae9 --- /dev/null +++ b/Hubs/Broadcaster.cs @@ -0,0 +1,17 @@ +using System.Threading.Tasks; +using Microsoft.AspNetCore.SignalR; + +namespace LiveGameFeed.Hubs +{ + public class Broadcaster : Hub + { + public override Task OnConnected() + { + return Clients.All.Message("New connection " + Context.ConnectionId); + } + public Task Broadcast(string message) + { + return Clients.All.Message(Context.ConnectionId + "> " + message); + } + } +} \ No newline at end of file