4

I know there are lots of examples out there to do with SignalR but I can't seem to get it working, I was hoping that one of you may be able to show (in full) how a WebPage (threaded loop so we can see it happening over and over) could call a JS method on a Page and change a text label or create a popup or, just something so that we an see the method execute?

I'll give you my code and maybe you can point out the error, but any basic example of Server->Client invocation without a Client first making a request would be amazing!

Hub:

[HubName("chat")]
public class Chat : Hub
{
    public void Send(string message)
    {
        // Call the addMessage method on all clients?
        Clients.addMessage(message);
    }
}

Calling (Threaded) method:

private void DoIt()
{
    int i = 0;
    while (true)
    {
        var hubContext = GlobalHost.ConnectionManager.GetHubContext<Chat>();
        hubContext.Clients.addMessage("Doing it... " + i);
        i++;
        Thread.Sleep(500);
    }
}

JS:

$(function () {
    // Proxy created on the fly
    var chat = $.connection.chat;

    // Declare a function on the chat hub so the server can invoke it
    chat.addMessage = function (message) {
        confirm("Are you having fun?");
        confirm(message);
    };

    // Start the connection
    $.connection.hub.start();        
});
4

1 回答 1

3

我遇到的问题是一个自关闭的 JS 导入标签,它停止了页面上正在运行的所有 JS ......

对于其他有同样问题的人,这是我在服务器上将数据推送到所有客户端的工作示例,而无需客户端的任何提示:

Javascript:

$(function () {
    // Proxy created on the fly
    var chat = $.connection.chat;

    // Declare a function so the hub can invoke it
    chat.addMessage = function (message) {
        document.getElementById('lblQuestion').innerHTML = message;
    };

    // Start the connection
    $.connection.hub.start();
});

HTML:

<h2 id="lblQuestion" runat="server">Please wait for a question...</h2>

中心:

[HubName("chat")]
public class Chat : Hub
{
    public void Send(string message)
    {
        // Call the addMessage method on all clients
        Clients.addMessage(message);
    }

    public void Broadcast(string message)
    {
        IHubContext context = GlobalHost.ConnectionManager.GetHubContext<Chat>();
        context.Clients.addMessage(message);
    }
}

致电客户:

private void DoIt()
{
    int i = 0;
    while (true)
    {
        var hubContext = GlobalHost.ConnectionManager.GetHubContext<Chat>();
        hubContext.Clients.addMessage("Doing it... " + i);
        i++;
        Thread.Sleep(500);
    }
}

对 DoIt() 的线程调用:

    var thread = new Thread(new ThreadStart(DoIt));

    thread.SetApartmentState(ApartmentState.STA);
    thread.Start();
于 2012-10-10T20:02:08.023 回答