Skip to content

Instantly share code, notes, and snippets.

@tocalai
Created September 2, 2019 02:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tocalai/137d85227a595ce30672ee3fa70fe781 to your computer and use it in GitHub Desktop.
Save tocalai/137d85227a595ce30672ee3fa70fe781 to your computer and use it in GitHub Desktop.
Service for broadcast sending all mock events to client(s)
using Microsoft.AspNetCore.SignalR;
using Newtonsoft.Json;
using SignalR.Lab.Web.Hubs;
using SignalR.Lab.Web.Models;
using System;
using System.Timers;
namespace SignalR.Lab.Web.Services
{
public class EventReceiverService
{
private readonly IHubContext<EventHub> _eventHub;
private Timer _mockEventGenTimer;
// DI EventHub
public EventReceiverService(IHubContext<EventHub> eventHub)
{
_eventHub = eventHub;
Init();
}
// initial timer for sending mock event to client side
private void Init()
{
_mockEventGenTimer = new Timer(3 * 1000)
{
AutoReset = false
};
_mockEventGenTimer.Elapsed += MockEventGenTimer_Elapsed; ;
}
public void StartReceive()
{
_mockEventGenTimer.Start();
Console.WriteLine("Start receiving..........");
}
private void MockEventGenTimer_Elapsed(object sender, ElapsedEventArgs e)
{
_mockEventGenTimer.Enabled = false;
var mockEvent = new EventModel()
{
Content = $"{new Random().Next()}"
};
// broadcast send message to all registered client(s)
_eventHub.Clients.All.SendAsync(nameof(IEventHub.SendNoticeEventToClient),
JsonConvert.SerializeObject(mockEvent)).GetAwaiter().GetResult();
_mockEventGenTimer.Enabled = true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment