Простой пример javascript-клиента Signalr Owin не вызывается

У меня есть версия 5.3.0 самостоятельного хостинга signalr, которая обновляется до более новой версии signalr. Использование https://github.com/SignalR/SignalR/wiki/Self-host пример Я создал простой пример, но не могу заставить его работать.

Я могу подключиться к хабу на сервере и вызвать методы на хабе, но я не могу заставить хаб вызвать клиент javascript.

Глядя на это в скрипаче, я никогда не вижу ответа от концентратора.

Вот код

using System;
using Microsoft.AspNet.SignalR;
using Microsoft.Owin.Hosting;
using Owin;



namespace ConsoleApplication3
{
class Program
{
    static void Main(string[] args)
    {
        string url = "http://localhost:8080/";

        using (WebApplication.Start<Startup>(url))
        {
            Console.WriteLine("Server running on {0}", url);
            Console.ReadLine();
        }
    }
}
}

using Microsoft.AspNet.SignalR;
using Owin;

namespace ConsoleApplication3
{
  class Startup
  {
    // This method name is important
    public void Configuration(IAppBuilder app)
    {
        var config = new HubConfiguration
        {
            EnableCrossDomain = true,
            EnableJavaScriptProxies = true
        };

        app.MapHubs(config);
    }

  } 

}

using System;
using System.Threading.Tasks;
using Microsoft.AspNet.SignalR;
using Newtonsoft.Json;

namespace ConsoleApplication3.Hubs
{
public class Chat : Hub
{

    public override Task OnConnected()
    {
        Notify(Context.ConnectionId);
        return new Task(() => { });
    }

    public void RunTest()
    {
        Notify(Context.ConnectionId);
    }


    public void Notify(string connectionId)
    {
        dynamic testMessage = new
        {
            Count = 3,
            Message = "Some test message",
            Timestamp = DateTime.Now
        };

        String json = JsonConvert.SerializeObject(testMessage);

        var context = GlobalHost.ConnectionManager.GetHubContext<Chat>();
        context.Clients.Client(connectionId).sendNotification(json);
    }

 }
}

А вот и клиентская часть

<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head>
<title></title>     
    <script src="Scripts/json2.js"></script>
    <script src="Scripts/jquery-1.9.1.js"></script>
    <script src="Scripts/jquery.signalR-1.0.1.js"></script>
    <script src="http://localhost:8080/signalr/hubs"></script>

<script>         
    $(function () {

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

        // Declare functions that can be run on the client by the server
        notification.client.sendNotification = onAddNotification;
        notification.client.disconnected = function (connectionid) {
            console.log(connectionid);
        };
        // Testing code only
        $("#testButton").click(function () {
            // Run test function on server
            notification.server.runTest();
        });

        jQuery.support.cors = true;

        // Map the onConnect and onDisconnect functions
        notification.client.connected = function () {
            alert("Notification system connected");
        };
        notification.client.disconnected = function () { };
        $.connection.hub.url = "http://localhost:8080/signalr";

        //$.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 ' + parsedDate + '</li>');

    };

    </script> 
</head> 
<body>     
    <a href="javascript:void(0)" class="btn" id="testButton">Send test</a>     
    <ul class="unstyled" id="notifications">             
    </ul> 
</body>

Any ideas would be appreciated, since i am fairly stuck.


person Kenneth Coughlin    schedule 13.04.2013    source источник


Ответы (1)


Несколько вещей в вашем коде:

Измените это:

public override Task OnConnected()
{
    Notify(Context.ConnectionId);
    return new Task(() => { });
}

To:

public override Task OnConnected()
{
    Notify(Context.ConnectionId);
    return base.OnConnected();
}

Также в вашем хабе:

Эта функция слишком старается:

public void Notify(string connectionId)
{
    dynamic testMessage = new
    {
        Count = 3,
        Message = "Some test message",
        Timestamp = DateTime.Now
    };

    String json = JsonConvert.SerializeObject(testMessage);

    var context = GlobalHost.ConnectionManager.GetHubContext<Chat>();
    context.Clients.Client(connectionId).sendNotification(json);
}

Я даже не уверен, почему вы передаете идентификатор соединения (может быть, он должен был быть статическим?)

public void Notify()
{
    dynamic testMessage = new
    {
        Count = 3,
        Message = "Some test message",
        Timestamp = DateTime.Now
    };

    Clients.Client(Context.ConnectionId).sendNotification(testMessage);
}

Вам не нужно сериализовать дважды, мы уже делаем это за вас.

Удалять:

jQuery.support.cors = true;

Никогда не устанавливайте это.

Также:

// Map the onConnect and onDisconnect functions
notification.client.connected = function () {
    alert("Notification system connected");
};

notification.client.disconnected = function () { };

Они ничего не отображают на стороне клиента. Вы не можете сопоставить подключенных и отключенных от сервера к клиенту. У клиента есть свои события.

Другие вещи:

Это должно быть внутри обратного вызова запуска, чтобы вы не нажали его, пока он не будет готов:

$.connection.hub.start().done(function() {
    // Testing code only
    $("#testButton").click(function () {
        // Run test function on server
        notification.server.runTest();
    });
});
person davidfowl    schedule 13.04.2013
comment
Спасибо, Дэвид, что сделал это. У меня сейчас проблема в том, что я подключаюсь к двум концентраторам по разным URL-адресам, и когда я это делаю: - code var cfgBrokerHubConnection = $.hubConnection(cfgBrokerSignalRHubServer); var cfgBroker = cfgBrokerHubConnection.createHubProxy('cfgBrokerHub'); я получаю сообщение об ошибке в этой строке cfgBroker.client.receiveMessage = processCfgMessage(m); говоря, что клиент не определен. - person Kenneth Coughlin; 14.04.2013
comment
Я сталкиваюсь с той же проблемой OnConnected, но не использую EnableJavaScriptProxies = true, и мой код здесь но исправил эту проблему. Теперь получаю идентификатор соединения, но OnConnected не срабатывает :( - person Developer; 06.11.2017