简体   繁体   English

使用 SignalR 向客户端发送消息

[英]Send message to Client with SignalR

I'm trying to send a message from the server to a specific client.我正在尝试从服务器向特定客户端发送消息。

This is my client class (console application)这是我的客户 class(控制台应用程序)

    static void Main(string[] args)
    {
        var connection = new HubConnectionBuilder()
            .WithUrl("https://localhost:5001/chathub")
            .Build();

        connection.StartAsync().Wait();
        connection.On("ReceiveMessage",(string message) =>
        {
            Console.Write(message);               
        });

        Console.ReadLine();
    }

My HubClass (asp.net mvc core)我的 HubClass(asp.net mvc 核心)

public class ChatHub : Hub
{
    public static ConcurrentDictionary<string, MyUserType> MyUsers = new ConcurrentDictionary<string, MyUserType>();

    public Task SendMessageToAll(string message)
    {
        return Clients.All.SendAsync("ReceiveMessage", message);
    }

    public Task SendMessageToUser(string connectionId, string message)
    {
        return Clients.Client(Context.ConnectionId).SendAsync("ReceiveMessage", message);
    }

    public override async Task OnConnectedAsync()
    {
        MyUsers.TryAdd(Context.ConnectionId, new MyUserType() { ConnectionId = Context.ConnectionId });

        await Clients.All.SendAsync("UserConnected", Context.ConnectionId);
        await base.OnConnectedAsync();
    }

    public override async Task OnDisconnectedAsync(Exception ex)
    {
        MyUserType garbage;
        MyUsers.TryRemove(Context.ConnectionId, out garbage);

        await Clients.All.SendAsync("UserDisconnected", Context.ConnectionId);
        await base.OnDisconnectedAsync(ex);
    }
}

public class MyUserType
{
    public string ConnectionId { get; set; }
}

Now how do I execute the Console.Write(message);现在我如何执行Console.Write(message); in the console application from the web app?在 web 应用程序的控制台应用程序中?

I've tried doing something like this:我试过做这样的事情:

ChatHub chatHub = new ChatHub();
chatHub.SendMessageToAll("test");

but the Clients is null in the ChatHub class.Clients是 ChatHub class 中的 null。

You can do something like below in your server:您可以在服务器中执行以下操作:

public class HomeController : Controller
{
    private readonly IHubContext<ChatHub> _hubContext;      
    public HomeController(IHubContext<ChatHub> hubContext)
    {
       _hubContext = hubContext;
    }

    public IActionResult CallClient()
    {
        //execute the client code
        _hubContext.Clients.All.SendAsync("ReceiveMessage", "test");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM