4

SignalR を使用する例がたくさんあることは知っていますが、それを機能させることができないようです。あなたの 1 人が (完全に) WebPage (スレッド化されたループを見ることができるように) を示すことができることを望んでいました何度も発生します) Page で JS メソッドを呼び出して、テキスト ラベルを変更したり、ポップアップを作成したり、メソッドの実行を確認できるようにするだけでしょうか?

私はあなたに私のコードを提供し、エラーを指摘できるかもしれませんが、クライアントが最初にリクエストを行わずに Server->Client を呼び出す基本的な例は素晴らしいでしょう!

ハブ:

[HubName("chat")]
public class Chat : Hub
{
    public void Send(string message)
    {
        // Call the addMessage method on all clients?
        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);
    }
}

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 に答える