客户端功能没有得到所谓的SignalR [英] Client Function Not getting called SignalR

查看:176
本文介绍了客户端功能没有得到所谓的SignalR的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Controller类中枢在哪里定义

    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的控制台应用程序类
第二类选择在这里枢纽定义控制器类

Actual screen 1st Selected class is the Console application class which is used for mapping server url 2nd Selected class is the controller class where hub is defined

我现在面临一个问题,当我拨打电话MyHub的对象,并从控制器调用它的函数获取调用,但是当我在屏幕上preSS发送按钮调用没有显示我的HTML页面上,另一方面同样的功能,但输出也显示在页面上。请告诉我,为什么会出现这种情况,如何等等HTMLpage表明输出well.I觉得我不指定URL枢纽的地方应该写从控制器调用函数这就是为什么它不调用客户端的功能,当我直接从控制器类从客户端,因为在客户端的聊天URL指定发送,而不是调用枢纽功能,我认为这就是为什么当我打电话从客户端页面端发送功能添加消息被执行。我是无法找到一个方法来指定地址枢纽

I am facing a problem when i make an object of call MyHub and call it from controller the function is getting called but nothing is displayed on my HTML page on the other hand when i press send button on screen it calls the same function but the output is also show on the page .Please tell me why is this happening and how to call function from controller so that output is shown on HTMLpage as well.I think I am not specifying hub URL where it should write and that's why it's not calling client side function when i send it directly from controller class instead of calling hub function from client side because in client side chat URL is specified and I think that's why when i call send function from client page client add message is executed.I am unable to find a way to specify address for hub

当我在屏幕上preSS发送按钮,会显示此日志消息:SignalR:关于集线器客户端触发事件枢纽方法addMessage'MyHub'。

When I press send button on screen ,This logging message is shown: SignalR: Triggering client hub event 'addMessage' on hub 'MyHub'.".

但是,当我把它从控制器GetMonitoringProfileLiveLogChart功能直接没有显示此日志记录信息。

But when I call it direct from controller in "GetMonitoringProfileLiveLogChart" function this logging message is not shown.

SignalR版本1.1.3

推荐答案

它看起来像什么应该在网页上显示,这是由于没有开始之前集线器开往集线器的客户端功能。

To me it looks like nothing should be displayed on the page, this is due to not having a client side function for your hub bound prior to starting your hub.

因此​​,要解决您的问题只需添加你的方法addMessage功能给客户之前枢纽您 $ connection.hub.start

Therefore to fix your issue just add your "addMessage" function to the client hub before you do $.connection.hub.start:

chat.client.addMessage = function() {...}

$.connection.hub.start().done(function() {...});

接下来您在code有几个误区:

Next you have a few errors in your code:


  1. 您正在做的基本上是两倍的document.ready,做 $(函数(){....})本质的document.ready,但是你也是做 $(文件)。就绪(函数(){...})中。

  2. 在集线器您是通过集线器背景下发送给客户。这工作,但没有必要这么做。你的方法是不是静态的,你应该能够做到 Clients.All.addMessage(...)

  1. You're essentially doing document.ready twice, doing $(function() {....}) is essentially document.ready, however you're ALSO doing $(document).ready(function() {...}) inside.
  2. In your hub you're sending to clients via the hubs context. This works, but there's no need to do it. Your method is not static and you should just be able to do Clients.All.addMessage(...).

这篇关于客户端功能没有得到所谓的SignalR的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆