SignalR介绍及Asp.net

发布时间:2018-09-24  栏目:法律  评论:0 Comments

      在Visual Studio
2012屡遭轻松将JSON数量易到POCO的代码,首先你用安装Web
Essentials
2012。在VS2012负,任何cs文件被单击右键就起这样的菜系:

     SignalR
是一个asp.net异步库,它提供广播消息及差不多独client端的编制。
SignalR能就此来始终如一客户端和劳动端的连接,让咱好开发一些实时的应用,例如聊天室在线预订系统,股票交易等实时应用。这可以明显下降服务器的载重确保无不必要的请求从更客户端请求。
SignalR是非微软的正统启幕源项目。
它们实现了Long
Polling的模式,可看下面图示:

图片 1

图片 2

 
    以这个
http://channel9.msdn.com/niners/CapSoft/achievements/visualstudio?json=true&raw=true 
URL也示范, 请求后将回来JSON数据:

风的 AJAX 应用不同之处在于:

{"Name":"CapSoft","FriendlyName":"JPHellemons","Achievements":[{"Name":"MoreThan10StepOver","CurrentNumber":11,"DateEarned":"2012-08-22T14:00:23.9742427+02:00"},{"Name":"UsedOrganizedUsings50Achievement","CurrentNumber":3},{"Name":"Regions10Achievement","DateEarned":"2012-01-19T16:04:10.7662105+01:00"},{"Name":"CloseAllButThis10Achievement","CurrentNumber":8},{"Name":"MoreThan10StepInto","CurrentNumber":11,"DateEarned":"2012-08-22T14:00:21.8049672+02:00"},{"Name":"ExtensionsAchievement5","DateEarned":"2012-03-15T09:37:43.3473414+01:00"},{"Name":"ExtensionsAchievement10","DateEarned":"2012-03-15T09:37:43.5283517+01:00"},{"Name":"InstallAndRegisterForAchievements","DateEarned":"2012-03-15T09:37:43.7173626+01:00"},{"Name":"BraveNewWorldAchievement","DateEarned":"2012-08-22T14:43:54.1176689+02:00"},{"Name":"ReferencedAssemblies25","DateEarned":"2012-08-22T14:44:54.1723276+02:00"},{"Name":"MoreThan1000LOC","DateEarned":"2012-08-23T09:39:37.8062693+02:00"},{"Name":"MoreThan30EnumFieldsAchievement","DateEarned":"2012-08-23T09:39:44.3466433+02:00"},{"Name":"LongerThan300LocAchievement","DateEarned":"2012-08-23T09:39:44.6546610+02:00"},{"Name":"EqualOpportunistAchievement","DateEarned":"2012-08-23T09:39:44.7196647+02:00"},{"Name":"GotoAchievement","DateEarned":"2012-08-28T09:55:57.0744434+02:00"},{"Name":"MoreThan10OverloadsAchievement","DateEarned":"2012-08-29T15:08:46.8305656+02:00"}]}
  1. 服务器端会阻塞请求直到来数据传递或过期才回来。
  2. 客户端 JavaScript
    响应处理函数会以拍卖完毕服务器返回的音信后,再次发出请求,重新成立连接。
    3.
    当客户端处理接收的多少、重新建立连接时,服务器端可能产生新的数量达;这些消息会叫劳动器端保存直到客户端重新建立连接,客户端会一差把目前服务器端所有的音讯取回。
 COPY这些数据剪贴版,执行 “Paste JSON as Classes”, 在IDE中我们马上生成这样的代码:



    public class Achievement

    {

        public string Name { get; set; }

        public int CurrentNumber { get; set; } public DateTime DateEarned { get; set; }

    }

 

    public class Parent

    {

        public string Name { get; set; }

        public string FriendlyName { get; set; } public Achievement[] Achievements { get; set; }

    }

 

  我们还没写任何代码,接下来我们从Nuget安装一个JSON.NET的类库,用写下面三行代码就轻易获得数据对象:

      WebClient wc = new WebClient();   

      string json = wc.DownloadString("http://channel9.msdn.com/niners/CapSoft/achievements/visualstudio?json=true&raw=true");    

      var data = JsonConvert.DeserializeObject<Parent>(json);

  
下我们来由此一个简便的小例,首先通过NuGet安装她:

   
好了,到此结束,由此可见我们编码越来越轻松了,实际上我们尚得处理JSONP的数量,希望对你支出帮带。

Install-Package SignalR

作者:Petter Liu
出处:http://www.cnblogs.com/wintersun/
正文版权归作者和博客园共有,欢迎转载,但未经作者同意要保留这个段子声明,且当篇章页面明显位置让有原文连接,否则保留追究法律责任的权。
拖欠文章吧同时公布于自我之单独博客中-Petter Liu
Blog。

在Server端,创建一个MyChat的Class继承自SignalR.Hubs.Hub类 :

    public class MyChat : Hub

    {

        /// <summary>

        /// Sends the specified message.

        /// </summary>

        /// <param name="message">The message.</param>

        public void Send(string message)

        {

            // Call the addMessage method on all clients         

            Clients.addMessage(message);

        }

    }

而今来拘禁前端页面,引用相应的客户端Js脚本,创建连接,绑定事件。

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

    <title>dev home</title>

</head>

<body>

    <script src="../Scripts/jquery-1.7.2.js"></script>

    <script src="../Scripts/jquery.signalR-0.5.2.js"></script>

    <script src="/signalr/hubs" type="text/javascript"></script>

    <div>

        <script type="text/javascript">

            var chat;

            $(function () {

                // Created proxy            

                chat = $.connection.myChat;

                // Assign a function to be called by the server        

                chat.addMessage = onAddMessage;

                // Register a function with the button click               

                $("#broadcast").click(onBroadcast);

                // Start the connection        

                $.connection.hub.start();

            });

            function onAddMessage(message) {

                // Add the message to the list         

                $('#messages').append('<li>' + message + '</li>');

            }

            function onBroadcast() {

                // Call the chat method on the server           

                chat.send($('#message').val());

            }       

        </script>

        <input type="text" id="message" />

        <input type="button" id="broadcast" value="send" />

        <ul id="messages">

        </ul>

    </div>

</body>

</html>

运行后,我们得望每次点击Button就会见将当下底消息播报及具有客户端。
使用Fiddler 结果是,当我们付出cc字符串的Request RAW:

POST http://localhost:17347/signalr/send?transport=longPolling&connectionId=8eaf7e6b-f0e9-414a-8e97-68ad7ff02e2b HTTP/1.1
Accept: application/json, text/javascript, */*; q=0.01
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
Referer: http://localhost:17347/mytest/MyChat.html
Accept-Language: zh-cn
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)
Host: localhost:17347
Content-Length: 131
Connection: Keep-Alive
Pragma: no-cache

data=%7B%22hub%22%3A%22MyChat%22%2C%22method%22%3A%22Send%22%2C%22args%22%3A%5B%22cc%22%5D%2C%22state%22%3A%7B%7D%2C%22id%22%3A1%7D

 

Response RAW:

 

HTTP/1.1 200 OK
Server: ASP.NET Development Server/10.0.0.0
Date: Thu, 19 Jul 2012 03:12:28 GMT
X-AspNet-Version: 4.0.30319
Cache-Control: private
Content-Type: application/json
Connection: Close
Content-Length: 66

{"State":{},"Result":null,"Id":"1","Error":null,"StackTrace":null}

 

接下来于Fiddler中扣第3单照面说话显示HTTP一直于维持连续,
上面文本是里第2个会话的RAW.

 

基于Long Polling,客户端有之请到劳动器端没有回复,直到来数据返回。
Web客户端保留挂于状态只有等到服务器返回一些行的响应才关闭连接。这正是今日我们怀念使之
–— 潜在减轻的 Web 服务器的下压力。

盼对您Web开发有帮助.

你可能感兴趣文章:

故此Knockoutjs与Asp.net
MVC实现级联下拉列表

 

作者:Petter Liu
出处:http://www.cnblogs.com/wintersun/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意要保留这个段子声明,且在文章页面明显位置给起原文连接,否则保留追究法律责任的权。
该篇为又披露以自己的独自博客中-Petter Liu
Blog。

留下评论