How do I send messages from server to client using SignalR Hubs

后端 未结 2 2024
小蘑菇
小蘑菇 2020-12-14 08:55

I am just starting to explore signalR and I would like to able to send messages from the server to all clients.

Here is my Hub

 using System;
using          


        
相关标签:
2条回答
  • 2020-12-14 09:16

    I think it should be

     void aTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            var context = GlobalHost.ConnectionManager.GetHubContext<Chat>();
            context.Clients.All.addMessage("Hello");      
        }
    

    instead. With Send you are calling the method used by the client to call the server...

    0 讨论(0)
  • 2020-12-14 09:37

    Yes you must set that line to:

    void aTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            var context = GlobalHost.ConnectionManager.GetHubContext<Chat>();
            context.Clients.All.addMessage("Hello");      
        }
    

    However this is only half way and still wont work.

    In your Js you need to write:

    $(function () {
    
    //Proxy created on the fly
    var chat = $.connection.chat;
    
    // Declare a function on the chat hub so the server can invoke it
    chat.client.addMessage = function (message) {
        $("#messages").append("<li>" + message + "</li>");
    };
    
    $("#broadcast").click(function () {
        // call the chat method on the server
        chat.client.addMessage($("#msg").val());
    });
    
    $.connection.hub.start();
    });
    

    I added the chat.clientthis will add a client-side hub method that the server will call.

    0 讨论(0)
提交回复
热议问题