2013-04-13 3 views
0

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

Я могу получить соединение с концентратором на сервере и вызвать методы на концентраторе, но я не могу получить хаб для вызова 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> 

Любые идеи будут оценены, так как я довольно застрял.

ответ

2

Немного вещей в вашем коде:

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

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(); 
    }); 
}); 
+0

Спасибо Дэвиду, что это сделал. Проблема, которую я сейчас имею в том, что я подключаюсь к двум концентраторам на разных URL-адресах, и когда я это делаю: - 'code' var cfgBrokerHubConnection = $ .hubConnection (cfgBrokerSignalRHubServer); var cfgBroker = cfgBrokerHubConnection.createHubProxy ('cfgBrokerHub'); Я получаю сообщение об ошибке в этой строке cfgBroker.client.receiveMessage = processCfgMessage (m); говоря, что клиент не определен. –

+0

https://github.com/SignalR/SignalR/wiki/SignalR-JS-Client-Hubs-%28No-Proxy%29 – davidfowl

+0

Я сталкиваюсь с той же проблемой OnConnected, но я не использую EnableJavaScriptProxies = true, а мой код [здесь ] (https://stackoverflow.com/questions/47138223/angular-signalr-error-during-negotiation-request), но исправил эту проблему. Теперь получение идентификатора соединения, но OnConnected не запускается :( – Developer

Смежные вопросы