4

概述

我在让我的 SignalR 服务器/集线器在我的 SignalR 客户端上调用 javascript 函数时遇到了真正的问题。

我试过的

  • 我已经阅读了更多的教程并查看了很多关于它应该如何工作的示例(包括官方文档),这几乎是荒谬的。
  • 我已经尝试注释掉除核心功能之外的所有功能。
  • 我已确保服务器和客户端功能不同且拼写正确。
  • 我也打开了登录,但 Firebug 控制台中没有出现任何错误。

环境

有问题的 SignalR 代码已在 ASP.net MVC4 项目中使用 VB.net 与 MySQL 和实体框架 v5 实现。我正在使用 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(消息);

每当调用 Hub 中的Notify函数时,实际上从不调用客户端函数!

其他有用的位

  1. 连接肯定是成功的,因为我可以在 Firebug 中看到连接长轮询。
  2. 在onConnectedGetUsersConnectionID函数中,我的用户连接已成功保存并从我的数据库中检索。
  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 控制台的一个示例... 萤火虫控制台


2013-04-05 更新

随着越来越多的测试和调试,我遇到了客户端函数何时调用和不调用的特征......

从我之前的更新中可以看出,SignalR 选择使用超时时间约为 35 秒的长轮询。

在对客户端函数进行了多次重复调用之后,似乎只有在长轮询生命的前 10 秒内进行的调用才能到达客户端并成功运行该函数。在这段时间之后发出的电话似乎没有打通。

我想这意味着我的代码是正确的,但为什么会这样?

SignalR 常见问题解答...

我还在这里找到了与我的问题类似的东西:SignalR Wiki FAQ's

我使用的是 Windows 7 Professional,但我没有使用 IIS(我使用的是 IIS Express),所以这可能是同一个问题吗?

4

0 回答 0