.net signalR 实例
2. Add Hub Class :
public class ServerTimeHub : Hub { public void PushServerTime() { Clients.All.addNews(DateTime.Now.ToString()); } /// <summary> /// call by client /// </summary> public void Subscribe() { var i = 0; while (i++ < 10) { Thread.Sleep(1000); PushServerTime(); } } }
3. Client Js :
@{ ViewBag.Title = "Signal R test"; } <h2>Messages</h2> <div class="container"> <ul id="messages"></ul> </div> @section scripts { <!--Script references. --> <!--The jQuery library is required and is referenced by default in _Layout.cshtml. --> <!--Reference the SignalR library. --> <script src="~/Scripts/jquery.signalR-2.1.2.min.js"></script> <!--Reference the autogenerated SignalR hub script. --> <script src="~/signalr/hubs"></script> <!--SignalR script to update the chat page and send messages.--> <script> $(function () { // Reference the auto-generated proxy for the hub. var proxy = $.connection.serverTimeHub; // Create a function that the hub can call back to display messages. proxy.client.addNews = function (message) { // Add the message to the page. $(‘#messages‘).append(‘<li>‘ + htmlEncode(message) + ‘</li>‘); }; // Start the connection. $.connection.hub.start().done(function () { proxy.server.subscribe(); }); }); // This optional function html-encodes messages for display in the page. function htmlEncode(value) { var encodedValue = $(‘<div />‘).text(value).html(); return encodedValue; } </script> }
4. Start up Add: App.MapSignalR();
public class Startup { public void Configuration(IAppBuilder app) { app.MapSignalR(); } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。