【问题标题】:Client Function Not getting called SignalR客户端功能没有被调用 SignalR
【发布时间】:2013-08-19 13:11:09
【问题描述】:

定义 Hub 的控制器类

    public abstract class MonitoringProfileLogChartController : Croem.NotificationManager.Website.Base.BaseController.BaseController
        {

            public ActionResult Index()
            {
                BusinessLogicReturn result = new ProcessBusinessLogic.Logic().GetRegisteredContexts();
                return base.TransalateToAction(result);
            }
            public ActionResult LiveMonitoringProfileLogChart()
            {
                return View();
            }
            public ActionResult test()
            {
                return View();
            }

**below is rest of the code of controller where our focus should be**


  public JsonResult GetMonitoringProfileLogChart(string FromDate, string ToDate, int ContextId)
        {
            BusinessLogicReturn result = new ProcessBusinessLogic.Logic().GetMonitoringProfileLogChart(FromDate, ToDate, ContextId);
            return Json(result.Model, JsonRequestBehavior.AllowGet);
        }
        public JsonResult GetMonitoringProfileLiveLogChart(string FromTime, string ToTime, string DataMinutes)
        {
            BusinessLogicReturn result = new ProcessBusinessLogic.Logic().GetMonitoringProfileLiveLogChart(FromTime, ToTime, DataMinutes);
            IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
            context.Clients.All.addMessage(result.Model);
            var hub = new MyHub();
            hub.Send("", "");
            return Json(result.Model, JsonRequestBehavior.AllowGet);

        }
        public JsonResult GetMonitoringProfileCombinationChart(string FromTime, string ToTime)
        {
            BusinessLogicReturn result = new ProcessBusinessLogic.Logic().GetMonitoringProfileCombinationChart(FromTime, ToTime);
            return Json(result.Model, JsonRequestBehavior.AllowGet);
        }
    }
    public class MyHub : Hub
    {
        IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
        public void Send(string name, string message)
        {

            BusinessLogicReturn result = new ProcessBusinessLogic.Logic().GetMonitoringProfileLiveLogChart(null, null, null);
            context.Clients.All.addMessage(result.Model);
        }
        public void test()
        {

            BusinessLogicReturn result = new ProcessBusinessLogic.Logic().GetMonitoringProfileLiveLogChart(null, null, null);
            context.Clients.All.addMessage(result.Model);

        }

    }

用于映射服务器 url 的控制台应用程序

class Program
{
    static void Main(string[] args)
    {
        string info = LoggingServer.Open();
        Console.WriteLine(info);

        string url = "http://localhost:8080";
        using (WebApp.Start<Startup>(url))
        {
            Console.WriteLine("Server running on {0}", url);
            var hubs = new Croem.NotificationManager.Website.Base.Controllers.MyHub();
            Console.ReadLine();
        }
        LoggingServer.Close();
    }
    class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // Turn cross domain on 
            var config = new HubConfiguration { EnableCrossDomain = true };

            // This will map out to http://localhost:8080/signalr by default
            app.MapHubs(config);
        }
    }

}

客户页面

<!DOCTYPE html>
<html>
<head>
    <title>SignalR Live Chat</title>

</head>
<body>
    <div class="container">
        <input type="text" id="message" />
        <input type="button" id="sendmessage" value="Send" />
        <input type="hidden" id="displayname" />
        <strong>Error Count</strong>
        <input type="text" id="Error_count" value="0" />
        <ul id="discussion"></ul>
    </div>
    <!--Script references. -->
    <!--Reference the jQuery library. -->
    <script src="Scripts/jquery-1.7.1.min.js"></script>
    <!--Reference the SignalR library. -->
    <script src="Scripts/jquery.signalR-1.1.3.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="http://localhost:8080/signalr/hubs"></script>
    <!--Add script to update the page and send messages.-->
    <script type="text/javascript">
        var chart;
        var timer;
        $(function () {



                Highcharts.setOptions({
                    global: {
                        useUTC: false
                    }
                });
                //Set the hubs URL for the connection
                $.connection.hub.url = "http://localhost:8080/signalr";

                // Declare a proxy to reference the hub.
                var chat = $.connection.myHub;

                // Create a function that the hub can call to broadcast messages.
                chat.client.addMessage = function (data) {

                    dataRecieved(data);
                    clearInterval(timer);
                    timer = setInterval(function () {
                        dataNotRecieved();
                    }, 10000);
                };
                $.connection.hub.logging = true;
                $.connection.hub.start().done(function () {
                    $('#sendmessage').click(function () {
                        // Call the Send method on the hub.
                        chat.server.send($('#displayname').val(), $('#message').val());
                        // Clear text box and reset focus for next comment.
                        $('#message').val('').focus();
                    });
                });

                $.ajax({
                    type: "GET",
                    dataType: "json",
                    data: {
                        DataMinutes: 5,
                        FromTime: null,
                        ToTime: null
                    },
                    url: "@Url.Action("GetMonitoringProfileLiveLogChart", "MonitoringProfileLogChart")",
                    success: function (data) {
                        chart = new Highcharts.Chart({
                            chart: {
                                renderTo: 'container',
                                type: 'spline',
                                animation: Highcharts.svg, // don't animate in old IE
                                marginRight: 10,


                            },
                            title: {
                                text: 'Live Profile Monitoring'
                            },
                            xAxis: {
                                type: 'datetime',

                                tickPixelInterval: 150
                            },
                            yAxis: {
                                title: {
                                    text: 'Value'
                                },
                                plotLines: [{
                                    value: 0,
                                    width: 1,
                                    color: '#808080'
                                }]
                            },
                            tooltip: {
                                formatter: function () {
                                    return '<b>' + this.series.name + '</b><br/>' +
                                    Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' +
                                    Highcharts.numberFormat(this.y, 2);
                                }
                            },
                            legend: {
                                enabled: true
                            },
                            exporting: {
                                enabled: false
                            },
                            series: data.series,

                        });
                    }
                });


                timer = setInterval(function () {
                    dataNotRecieved();
                }, 10000);

                function dataNotRecieved() {
                    var shift = false;
                    for (var j = 0; j < chart.series.length; j++) {
                        if (chart.series[j].data.length < 50) {
                            shift = false;

                        }
                        else {
                            shift = true;
                        }
                        chart.series[j].addPoint([new Date().getTime() - 4 * 1000 * 60 * 60, 0], true, shift);
                    }

                }
                function dataRecieved(data) {
                    // checking if series exsist in chart but is not in data coming from ajax call . and if it does not exsist add that series point with zero
                    var series_name_exist = 0;
                    var series_exist = 0;
                    var index = 0;
                    var shift = false;
                    var length = chart.series.length;
                    for (var j = 0; j < chart.series.length; j++) {

                        for (var k = 0; k < data.series.length; k++) {
                            if (chart.series[j].name == data.series[k].name) {
                                series_name_exist = 1;
                                break;
                            }

                        }
                        if (series_name_exist == 0) {

                            if (chart.series[j].data.length < 50) {
                                shift = false;

                            }
                            else {
                                shift = true;
                            }
                            chart.series[j].addPoint([new Date().getTime() - 4 * 1000 * 60 * 60, 0], true, shift);
                        }
                        else {
                            series_name_exist = 0;
                        }



                    }
                    //  if series exist add point otherwise add series
                    for (var k = 0; k < data.series.length; k++) {

                        for (var j = 0; j < chart.series.length; j++) {
                            if (chart.series[j].name == data.series[k].name) {
                                series_exist = 1;
                                index = j;
                                break;
                            }

                        }
                        if (series_exist == 1) {

                            if (chart.series[index].data.length < 50) {
                                shift = false;

                            }
                            else {
                                shift = true;
                            }
                            //chart.series[index].addPoint([data.series[k].time, data.series[k].count], true, shift);
                            chart.series[index].addPoint([new Date().getTime() - 4 * 1000 * 60 * 60, data.series[k].count], true, shift);
                            series_exist = 0;

                        }

                        else {

                            chart.addSeries({ name: '' + data.series[k].name + '', data: [] });
                            //chart.series[length].addPoint([data.series[k].time, data.series[k].count], true);
                            chart.series[length].addPoint([new Date().getTime() - 4 * 1000 * 60 * 60, data.series[k].count], true);
                            length = length + 1;
                        }


                    }
                }



                $('#message').focus();
                // Start the connection.


        });

    </script>
    <div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>

</body>
</html>

实际画​​面 第一个选择的类是用于映射服务器 url 的控制台应用程序类 2nd Selected 类是定义集线器的控制器类

当我创建一个调用 MyHub 的对象并从控制器调用它时,我遇到了一个问题,该函数被调用但另一方面,当我按下屏幕上的发送按钮时,我的 HTML 页面上没有显示任何内容但输出也显示在页面上。请告诉我为什么会发生这种情况以及如何从控制器调用函数以便输出也显示在 HTMLpage 上。我想我没有指定它应该写入的集线器 URL,这就是它的原因当我直接从控制器类发送它而不是从客户端调用集线器函数时不调用客户端函数,因为在客户端聊天 URL 中指定了,我认为这就是为什么当我从客户端页面调用发送函数时执行添加消息。我是无法找到指定集线器地址的方法

当我按下屏幕上的发送按钮时,会显示此日志消息:SignalR: Triggering client hub event 'addMessage' on hub 'MyHub'。”。

但是当我在“GetMonitoringProfileLiveLogChart”函数中直接从控制器调用它时,不会显示此日志消息。

SignalR 1.1.3 版

【问题讨论】:

    标签: javascript asp.net-mvc-4 signalr signalr-hub signalr.client


    【解决方案1】:

    在我看来,页面上似乎不应该显示任何内容,这是因为在启动集线器之前没有绑定集线器的客户端功能。

    因此,要解决您的问题,只需在执行 $.connection.hub.start 之前将“addMessage”函数添加到客户端集线器:

    chat.client.addMessage = function() {...}
    
    $.connection.hub.start().done(function() {...});
    

    接下来你的代码中有一些错误:

    1. 您实际上是在执行 document.ready 两次,执行 $(function() {....}) 本质上是 document.ready,但是您也在内部执行 $(document).ready(function() {...})
    2. 在您的集线器中,您通过集线器上下文发送给客户端。这行得通,但没有必要这样做。你的方法不是静态的,你应该能够做到Clients.All.addMessage(...)

    【讨论】:

    • 你可以直接从服务器推送消息到客户端而不需要从客户端调用它吗?
    • 您自己托管了一个服务器,然后看起来您的网站有一个单独的服务器。您的 JS 客户端正在连接到 Self Host 服务器,因此当您调用服务器端函数时,它会得到适当的响应。但是,由于您的控制器似乎位于不同的应用程序域中,因此它们不会与自托管服务器共享相同的 SignalR 服务器。因此,您的控制器无法发送到连接到您自己的主机服务器的客户端,这就是您看不到响应的原因。
    • 如果您想保持相同的架构,无论何时您希望您的网站调用客户端上的功能,您都可以将您的网站发布到您的自托管服务器;然后您的自托管服务器可以调用客户端上的方法。这涉及在您的自托管服务器上设置一个端点来处理传入的帖子并正确处理它们。当然,如果您不想保留架构,您可以将所有 SignalR 逻辑移动到您的网站上,那么一旦您将所有内容重新指向它,一切都会正常工作。
    • 嗯,我试过了,但没用,你能帮我做个伪代码还是编辑这段代码?
    • 你是个天才..我必须在我的控制器文件夹中安装这个包“Install-Package Microsoft.AspNet.SignalR.Client”,然后我必须在测试函数中这样做:var hubConnection = new Microsoft.AspNet.SignalR.Client.Hubs.HubConnection("localhost:8080"); var chat = hubConnection.CreateHubProxy("myHub"); hubConnection.Start().Wait(); chat.Invoke("Send", / /参数);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-22
    • 2015-12-08
    • 1970-01-01
    • 1970-01-01
    • 2012-07-17
    相关资源
    最近更新 更多