【问题标题】:Signalr Owin simple example javascript client not being calledSignalr Owin 简单示例 javascript 客户端未被调用
【发布时间】:2013-04-13 19:26:10
【问题描述】:

我有一个 5.3.0 版本的信号器自托管,它正在升级到更新版本的信号器。 使用https://github.com/SignalR/SignalR/wiki/Self-host 示例我创建了一个简单的示例,但我无法让它工作。

我可以连接到服务器上的集线器并调用集线器上的方法,但我无法让集线器调用 javascript 客户端。

在 fiddler 中查看它时,我从未看到集线器返回响应。

这里是代码

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>

任何想法都将不胜感激,因为我被卡住了。

【问题讨论】:

    标签: signalr signalr-hub signalr.client owin


    【解决方案1】:

    代码中的一些内容:

    改变这个:

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

    收件人:

    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);
    }
    

    我什至不确定您为什么要传递连接 ID(也许它本来是静态的?)

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

    【讨论】:

    • 感谢大卫这样做。我现在遇到的问题是我连接到不同 url 上的两个集线器,当我这样做时:-code var cfgBrokerHubConnection = $.hubConnection(cfgBrokerSignalRHubServer); var cfgBroker = cfgBrokerHubConnection.createHubProxy('cfgBrokerHub');我在这条线上遇到错误 cfgBroker.client.receiveMessage = processCfgMessage(m);说客户端未定义。
    • 我面临同样的 OnConnected 问题,但我不使用 EnableJavaScriptProxies = true 并且我的代码是 here 但修复了这个问题。现在获取连接 ID 但未触发 OnConnected :(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-14
    • 1970-01-01
    • 2018-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多