码迷,mamicode.com
首页 > Web开发 > 详细

.net signalR 实例

时间:2014-10-02 19:19:03      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   io   os   ar   for   sp   

1. install signalr for asp.net

bubuko.com,布布扣


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


.net signalR 实例

标签:des   style   blog   http   io   os   ar   for   sp   

原文地址:http://blog.csdn.net/lan_liang/article/details/39737523

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!