private static async Task TryGetAndPostMessages(CancellationToken ct) { //Demo Test: Generating Random messages at random intervals and send it to clients Random rnd = new Random(); await Task.Delay(rnd.Next(1000, 3000), ct); if (ct.IsCancellationRequested) return; Client[] clients = _clients.Values.ToArray(); Array.ForEach(clients, async (client) => { SSEMessage msg = new SSEMessage() { clientID = client.id, payload = new Payload { message = getQuote() } }; bool res = await PostMessage(msg); }); }
public static async Task<bool> PostMessage(SSEMessage message) { Client client; int cnt = _clients.Count(); if (_clients.TryGetValue(message.clientID, out client)) { try { if (message.payload.message == "DUMMY") { client.UpdateAccessTime(); } else { string data = JsonConvert.SerializeObject(message.payload); await client.WriteAndSend(data); } return true; } catch (System.Web.HttpException) { _RemoveClient(client.id); } catch (Exception) { //also needs to log here _RemoveClient(client.id); } return false; } else return false; }
private static async Task TryGetAndPostMessages(CancellationToken ct) { //Demo Test: Generating Random messages at random intervals and send it to random clients Random rnd = new Random(); await Task.Delay(rnd.Next(1000, 5000), ct); if (ct.IsCancellationRequested) return; Client client = null; //Get one Random client lock (_clients) { int cnt = _clients.Count(); if (cnt > 0) { int num = rnd.Next(100000) % cnt; client = _clients.Skip(num).Take(1).Select(c=>c.Value).First(); } } if (client == null) return; /* //Remove the clients after random intervals simulating different task times for each client if (DateTime.Now - client.CreatedTime > TimeSpan.FromSeconds(rnd.Next(60, 180))) { RemoveClient(client.id); return; } */ string[] words = new string[] { "Test", "How", "Messaging", "Working", "Random", "Words", "For", "Demo", "Purposes", "Only", "Needed" }; string message = "<b>Quote of the day</b>: <i>"+ string.Join(" ", words.Select(w => words[rnd.Next(0, 10)]).ToArray())+"</i>"; SSEMessage msg = new SSEMessage() { clientID = client.id, payload = new Payload { message = message } }; bool res = await PostMessage(msg); }