【问题标题】:Implementing WebSockets using SignalR使用 SignalR 实现 WebSocket
【发布时间】:2014-02-12 03:44:24
【问题描述】:

我正在尝试在我的 ASP.NET MVC Web 应用程序中使用 websockets,但我无法实现,所以在这里我尝试在最终用户网页上显示每个数据库更新,而无需刷新.

HTML:

<span id="nbAlertes"></span>
<ul id="listeAlertes"></ul>

Javascript / SignalR / jQuery

<!--Reference the SignalR library. -->
<script src="Scripts/jquery.signalR-2.0.2.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="signalr/hubs"></script>
<script>
 $(function () {
        // Declare a proxy to reference the hub.
        var alertes = $.connection.AlerteHub;
        // Create a function that the hub can call to broadcast messages.
        alertes.client.broadcastMessage = function (nbAlertes, listeAlertes) {
            // Html encode display name and message.
            var nbA = $('<div />').text(nbAlertes).html();
            var lstA = $('<div />').text(listeAlertes).html();
            // Add the message to the page.
            $('#nbAlertes').text(nbA);
            lstA.forEach(function(item) {
                $('#listeAlerte').append(item.nomPoste);
            });
        };
    });
</script>

类 AlerteHub:

public class AlerteHub : Hub
    {
        public void GetAll()
        {
            var nbAlertes = new CalculAlertesUtilitaire().compter();
            var listeAlertes = new CalculAlertesUtilitaire().lister(5);

            // Call the broadcastMessage method to update clients.
            Clients.All.broadcastMessage(nbAlertes, listeAlertes);
        }

MonitoringNDataContext _db = new MonitoringNDataContext();

public string compter()
    {
        var compte = _db.Alertes.ToList().Count();
        return (compte == 0) ? "" : compte.ToString();
    }

    public ICollection<AlerteModel> lister(int nb)
    {
        return (ICollection<AlerteModel>)_db.Alertes.ToList().Take(nb).ToArray();
    }
    }

类启动

public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // Any connection or hub wire up and configuration should go here
            app.MapSignalR();
        }
    }

请问我该怎么做呢?

【问题讨论】:

  • 如何它不起作用?会爆炸吗?
  • 当我更新数据库时,加载的网页没有更新。
  • 您在控制台和网络选项卡中看到了什么?
  • 需要在客户端声明参数。
  • @SLaks,我已经根据参数更新了我的帖子。

标签: javascript jquery asp.net-mvc websocket signalr


【解决方案1】:

如果要使用 SignalR,需要在客户端建立连接。在 JavaScript 中,您通过调用 connection.start() 来完成此操作。例如:

<!--Reference the SignalR library. -->
<script src="/Scripts/jquery.signalR-2.0.2.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="/signalr/hubs"></script>
<script>
 $(function () {
        // Declare a proxy to reference the hub.
        var alertes = $.connection.alerteHub;
        // Create a function that the hub can call to broadcast messages.
        alertes.client.broadcastMessage = function (nbAlertes, listeAlertes) {
            // Html encode display name and message.
            var nbA = $('<div />').text(nbAlertes).html();
            var lstA = $('<div />').text(listeAlertes).html();
            // Add the message to the page.
            $('#nbAlertes').text(nbA);
            lstA.forEach(function(item) {
                $('#listeAlerte').append(item.nomPoste);
            });
        };

        $.connection.hub.start().done(function () {
             // You should probably be calling GetAll from somewhere.
             // I'm not sure if you should call it as soon as you connect,
             // but you certainly can't call GetAll before connecting.
             alertes.server.getAll();
        }).fail(function (error) {
             alert("Failed to connect!");
        });
    });
</script>

您可以在此处了解有关如何使用 Signalr JS 客户端的更多信息:http://www.asp.net/signalr/overview/signalr-20/hubs-api/hubs-api-guide-javascript-client

【讨论】:

  • 您能否提供更多关于这种“行不通”的方式的详细信息?
  • 指的是调试器它说The script debugger failed to connect to the target process. A debugger is already attached.
  • 这是因为在您调试 Web 项目时,Visual Studio 默认会将自身附加为 JavaScript 调试器。这将使您无法使用 IE 的 F12 开发工具,直到 VS 分离。或者,您可以在 Chrome 或 FireFox 等其他浏览器中调试 JS。
  • 感谢您告诉我,我尝试使用 Chrome 进行调试,但出现以下错误:event.returnValue is deprecated. Please use the standard event.preventDefault() instead.Uncaught TypeError: Object [object Object],[object Object],[object Object],[object Object],[object Object] has no method 'forEach'。我已在相关数据库中插入了一个附加行,但网页显示中没有更新。
  • 我已经编辑了您的帖子并将解决方案写入其中。谢谢你的帮助伙计!!