4

概要

SignalR サーバー/ハブを取得して、SignalR クライアントで JavaScript 関数を呼び出すのに実際に問題があります。

私が試したこと

  • 私はより多くのチュートリアルを読み、これがどのように機能するかの非常に多くの例 (公式ドキュメントを含む) を見たので、ほとんどばかげています。
  • コア機能以外はすべてコメントアウトしてみました。
  • サーバーとクライアントの機能が同じではなく、スペルが正しいことを確認しました。
  • ログオンもオンにしましたが、Firebug コンソールにエラーは表示されませんでした。

環境

問題の SignalR コードは、VB.net と MySQL および Entity Framework v5 を使用して、ASP.net MVC4 プロジェクトに実装されています。IISExpress を使用して Visual Studio 2012 のローカル開発マシンでシステムをデバッグしています。

コード スニペット

グローバル.asax.vb:

Sub Application_Start()

    MiniProfilerEF.Initialize()

    AreaRegistration.RegisterAllAreas()

    ' Register the default hubs route: ~/signalr
    RouteTable.Routes.MapHubs()

    WebApiConfig.Register(GlobalConfiguration.Configuration)
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters)
    RouteConfig.RegisterRoutes(RouteTable.Routes)
    BundleConfig.RegisterBundles(BundleTable.Bundles)
    AuthConfig.RegisterAuth()

    ' Register custom view
    ViewEngines.Engines.Add(New CustomViewEngine())

End Sub

SignalR の初期化 JavaScript:

$(function () {

    // Proxy created on the fly
    var notification = $.connection.notificationHub;
    //$.connection.notificationHub.logging = true;

    // Declare functions that can be run on the client by the server
    notification.client.sendNotification = onAddNotification;

    // Testing code only
    $("#testButton").click(function () {
        // Run test function on server
        notification.server.runTest();
    });

    // Map the onConnect and onDisconnect functions
    notification.client.connected = function () { };
    notification.client.disconnected = function () { };

    //$.connection.hub.start();
    $.connection.hub.start(function () {
        alert("Notification system connected");
    });
});

// Process a newly received notification from the server
function onAddNotification(message) {

    // Convert the passed json message back into an object
    var obj = JSON.parse(message);

    var parsedDate = new Date(parseInt(obj.Timestamp.substr(6)));

    // Update the notification list
    $('#notifications').prepend('<li>' + obj.Message + ' at ' + dateFormat(parsedDate, "default") + '</li>');

    // Update the new notification count
    var count = document.getElementById("notification_count")
    if (count.textContent) {
        //W3C DOM
        count.textContent = obj.Count;
    } else if (anchor.innerText) {
        //Microsoft DOM
        count.innerText = obj.Count;
    }
    //document.getElementById("notification_count").innerHTML = obj.Count + '<i class="splashy-comment"></i>';

    // Show a brief notification message
    $.sticky(obj.Message, { autoclose: 2000, position: "top-right", type: "st-info" });

};

ハブ クラス:

Public Class NotificationHub
Inherits Hub

ReadOnly Group As String = "Notification"

Public Function RunTest()
    Dim testMessage As New SignalR_Notification_Message

    testMessage.Count = 3
    testMessage.Message = "Some test message"
    testMessage.Timestamp = Now

    Call Notify(testMessage, "joebloggs")
End Function

Public Overrides Function OnConnected() As Task

    Dim db As New MyEntities
    Dim userName As String = Context.User.Identity.Name
    Dim connectionID = Context.ConnectionId

    Dim conn As SignalR_Connection

    ' Attempt to find a retrieve a connection entry with the same Connection ID
    conn = db.SignalR_Connection.Where(Function(s) s.Connection_ID = connectionID).FirstOrDefault

    ' If the connection does not already exist, add it
    If IsNothing(conn) Then
        conn = New SignalR_Connection

        ' Create the new connection entry
        conn.Connection_ID = connectionID
        conn.Username = userName
        conn.Group = Group

        ' Attempt to save the new connection entry
        Try
            db.SignalR_Connection.Add(conn)
            db.SaveChanges()
        Catch ex As Exception
            Dim a As String = ""
            a = ""
        End Try
    End If

    Return MyBase.OnConnected()
End Function

Public Overrides Function OnDisconnected() As Task

    Dim db As New MyEntities
    Dim userName As String = Context.User.Identity.Name
    Dim connectionId As String = Context.ConnectionId

    Dim conn As SignalR_Connection

    ' Attempt to find a retrieve the connection entry
    conn = db.SignalR_Connection.Where(Function(s) s.Connection_ID = connectionId And s.Username = userName).FirstOrDefault

    ' Attempt to remove the connection entry
    Try
        db.SignalR_Connection.Remove(conn)
        db.SaveChanges()
    Catch ex As Exception
        Dim a As String = ""
        a = ""
    End Try

    Return MyBase.OnDisconnected()
End Function

''' <summary>
''' Send the notification to the client
''' </summary>
Public Sub Notify(Message As SignalR_Notification_Message, Username As String)

    Dim ConnectionIDs As List(Of String)
    Dim Serializer As New JavaScriptSerializer()
    Dim json As String

    ' Attempt to convert the object into json before sending
    Try
        json = Serializer.Serialize(Message)
    Catch ex As Exception
        Exit Sub
    End Try

    ' Get the connection id's this message must go to
    ConnectionIDs = GetUsersConnectionID(Username)

    If Not IsNothing(ConnectionIDs) Then
        ' Send the message to all connection ID's
        For Each ConnectionID In ConnectionIDs
            Clients.Client(ConnectionID).sendNotification(json)
        Next
    End If

End Sub

''' <summary>
''' Retrieve a list of connection ID's for the current user
''' </summary>
Public Function GetUsersConnectionID(Username As String) As List(Of String)

    Dim db As New MyEntities

    ' Attempt to find a retrieve the connection entries
    Return db.SignalR_Connection.AsNoTracking.Where(Function(s) s.Username = Username).Select(Function(s) s.Connection_ID).ToList

End Function

End Class

HTML (部分表示):

@ModelType Geo_sight.NotificationWindowModel

<div class="modal hide fade" id="myNotifications">
<div class="modal-header">
    <button class="close" data-dismiss="modal">×</button>
    <h3>Notifications</h3>
</div>
<div class="modal-body">
    <ul class="unstyled" id="notifications">
        @For Each Notification In Model.Notifications
            @<li>@Html.Raw(Notification.Text)</li>
        Next
    </ul>
</div>
<div class="modal-footer">
    <a href="javascript:void(0)" class="btn" id="testButton">Send test</a>
</div>

問題

onAddNotification関数の最初の行にブレークポイントを設定すると、次のようになります。

var obj = JSON.parse(メッセージ);

ハブのNotify関数が呼び出されるたびに、クライアント関数が実質的に呼び出されることはありません。

その他の便利なビット

  1. Firebug で接続がロング ポーリングされていることがわかるので、接続は確実に成功しています。
  2. ユーザー接続は、 onConnected関数とGetUsersConnectionID関数でデータベースから正常に保存および取得されています。
  3. サーバーからクライアント関数を実行しようとした数十回のうち(testButtonを使用してハブで通知呼び出しを開始しました)、3〜4回しか実行されませんでした。繰り返すことができました。
  4. 関数が実行される非常にまれでランダムな機会に、関数は本来の動作を実行し、クライアントのブレークポイントで関数の実行を停止することができました。
  5. ~/signalr/hubsスクリプトを確認しましたが、クライアント関数の定義の下には何もリストされていませんが、サーバー用です (以下を参照)。これは正しいです?クライアント機能がここにあるはずだと思いますか?

    proxies.notificationHub = this.createHubProxy('notificationHub'); 
    proxies.notificationHub.client = { };
    proxies.notificationHub.server = {
        getUsersConnectionID: function (Username) {
            return proxies.notificationHub.invoke.apply(proxies.notificationHub, $.merge(["GetUsersConnectionID"], $.makeArray(arguments)));
         },
    
        notify: function (Message, Username) {
            return proxies.notificationHub.invoke.apply(proxies.notificationHub, $.merge(["Notify"], $.makeArray(arguments)));
         },
    
        runTest: function () {
            return proxies.notificationHub.invoke.apply(proxies.notificationHub, $.merge(["RunTest"], $.makeArray(arguments)));
         }
    };
    
    return proxies;
    

2013-04-04 更新

もう少しデバッグを行うと、前の signalR 送信呼び出しが終了してから数秒後にテスト ボタンを何度も押すだけで、完全にランダムに、非常に時折クライアントを実行できます。

これは、Firebug コンソールからの例です... Firebug コンソール


2013-04-05 更新

テストとデバッグを重ねるうちに、クライアント関数が呼び出すときと呼び出さないときの特徴に出くわしました...

前回の更新でわかるように、SignalR は約 35 秒のタイムアウトでロング ポーリングを使用することを選択しました。

クライアント関数に対して何度も繰り返し呼び出しを行った結果、ロング ポーリング ライフの最初の約 10 秒以内に行われた呼び出しのみがクライアントに到達し、関数を正常に実行したようです。この期間以降に送信された呼び出しは、接続されていないようです。

これは私のコードが健全であることを意味すると思いますが、なぜこれが起こっているのですか??

SignalR FAQ の質問...

また、ここで私の問題に似たものを見つけました: SignalR Wiki FAQ's

Windows 7 Professional を使用していますが、IIS を使用していません (IIS Express を使用しています)。これは同じ問題でしょうか?

4

0 に答える 0