File: WeatherHub.cs

package info (click to toggle)
pysignalr 1.3.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 468 kB
  • sloc: python: 1,192; cs: 121; xml: 37; makefile: 28
file content (51 lines) | stat: -rw-r--r-- 1,983 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
using Microsoft.AspNetCore.SignalR;

namespace AspNetAuthExample.Hubs;

// Define a SignalR Hub for weather updates
public class WeatherHub : Hub
{
    // Method to send a message to all connected clients
    public async Task SendMessage(string user, string message)
    {
        await Clients.All.SendAsync("ReceiveMessage", user, message);
    }

    // Method to send a message to a specific group
    public async Task SendMessageToGroup(string groupName, string user, string message)
    {
        await Clients.Group(groupName).SendAsync("ReceiveMessage", user, message);
    }

    // Method to add a client to a group
    public async Task AddToGroup(string groupName)
    {
        await Groups.AddToGroupAsync(Context.ConnectionId, groupName);
        await Clients.Group(groupName).SendAsync("ReceiveMessage", "System", $"{Context.ConnectionId} has joined the group {groupName}.");
    }

    // Method to remove a client from a group
    public async Task RemoveFromGroup(string groupName)
    {
        await Groups.RemoveFromGroupAsync(Context.ConnectionId, groupName);
        await Clients.Group(groupName).SendAsync("ReceiveMessage", "System", $"{Context.ConnectionId} has left the group {groupName}.");
    }

    // Method to send the weather forecast to all clients
    public async Task SendWeatherForecast(string forecast)
    {
        await Clients.All.SendAsync("ReceiveWeatherForecast", forecast);
    }

    /// <summary>
    /// Trigger client result by invokeAsync method
    /// </summary>
    /// <param name="user"></param>
    /// <param name="message"></param>
    public async Task TriggerResultRequired(string user, string message)
    {
        var response = await Clients.Client(Context.ConnectionId).InvokeAsync<string>("ResultRequired", "Reply this message", CancellationToken.None);
        if (response == "Reply message")
            await Clients.Client(Context.ConnectionId).SendAsync("SuccessReceivedMessage", user, message);
    }
}