不用找了,比较全的signalR例子已经为你准备好了.

 这几天想着将一个winform的工具上线到web上,因为对时时性的要求比较高,找朋友咨询了一下推荐了SignlarR 框架,比较强大.昨天才看到,今天研究了一下将里面的例子都拿出来共享.

 官方的参考:http://www.asp.net/signalr/overview/getting-started

 安装SignalR: NuGet命令:

 PM> Install-Package Microsoft.AspNet.SignalR

 

<------------1:与他人聊天:------------>

后台代码示例:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using Microsoft.AspNet.SignalR;
 6 using Microsoft.AspNet.SignalR.Hubs;
 7 
 8 namespace SignalRChat.Hubs.Data
 9 {
10     [HubName("ViewDataHub")]
11     public class ViewDataHub : Hub
12     {
13         //this is just called by client and return the value for it .
14         public string Hello()
15         {
16             return "hello";
17         }
18 
19 
20 
21         //this fucntion will be called by client and the inside function 
22         //Clients.Others.talk(message);
23         //will be called by clinet javascript function .
24         public void SendMessag(string message)
25         {
26             Clients.Others.talk(message);
27         }
28 
29     }
30 }
View Code

 

小提示:注意其它的红色字体部分

前台代码示例:

 1 <!DOCTYPE html>
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4     <title></title>
 5     <!--Script references. -->
 6     <!--Reference the jQuery library. -->
 7     <script src="Scripts/jquery-1.10.2.min.js"></script>
 8     <!--Reference the SignalR library. -->
 9     <script src="Scripts/jquery.signalR-2.0.2.js"></script>
10     <!--Reference the autogenerated SignalR hub script. -->
11     <script src='signalr/hubs'></script>
12     <!--Add script to update the page and send messages.-->
13     <script type='text/javascript'>
14 
15 
16         $(function () {
17             // Declare a proxy to reference the hub.
18             var chat = $.connection.ViewDataHub;
19 
20 
21             //init the client function 
22             init(chat);
23 
24 
25             $("#btnclick").click(function () {
26                 //Response the information
27                 $.connection.hub.start().done(function () {
28                     chat.server.hello().done(function (res) {
29                         alert(res);
30                     })//end of done function
31                 })//the end of the $.connection
32             })//end of click function
33 
34 
35 
36             $("#btntalk").click(function () {
37                 $.connection.hub.start().done(function () {
38                     chat.server.sendMessag($("#txttalk").val());
39                     $("#txttalk").val("");
40                 })//the end of the $.connection
41 
42             });//btntalk end
43 
44         })
45 
46 
47         //init the client method
48         function init(chat) {
49 
50             chat.client.talk = function (message) {
51                 var talk = "<h1>" + message + "</h1>";
52 
53                 $("#dvtalk").append(talk);
54 
55             } //end regist the client function
56 
57         } //end of the initfunction
58 
59     </script>
60 </head>
61 <body>
62     <div>
63         <table id="tbtoday"></table>
64         <input type="text" id="txttalk" width="150"/>
65         <input type="button" id="btnclick" value="clickme" />
66         <input type="button" id="btntalk" value="talkwithme" />
67         <div id="dvtalk">
68 
69         </div>
70     </div>
71 </body>
72 </html>
View Code

 

出现的效果:

两个窗口之间的聊天

 

我知道你心中肯定有疑问,我也是这样,当我刚接触的时候完全搞不懂这是为什么会这样,我们来回顾一次正常的聊天过程:

那我们重新拆分以上的方法来证明我们的猜想是否正确

1          $("#btntalk").click(function () {
2                 $.connection.hub.start().done(function () {
3                     chat.server.sendMessag($("#txttalk").val());
4                     $("#txttalk").val("");
5                 })//the end of the $.connection
6 
7             });//btntalk end

 

chat.server.sendMessage(message) 从客户端调用了服务器的方法(服务器扮演的是中转站的角色).

此时的message 从客户端A发送给了服务端

那服务器就应该有这样的一个方法与之相对应

后台代码:

1    //this fucntion will be called by client and the inside function 
2         //Clients.Others.talk(message);
3         //will be called by clinet javascript function .
4         public void SendMessag(string message)
5         {
6             Clients.Others.talk(message);
7         }

服务端接收到A发送来的message.

这个时候服务端将消息推送给客户端B

Clients.Others.talk(message);

这个时候客户端B应该有一个talk的方法来将消息显示出来

 1   //init the client method
 2         function init(chat) {
 3 
 4             chat.client.talk = function (message) {
 5                 var talk = "<h1>" + message + "</h1>";
 6 
 7                 $("#dvtalk").append(talk);
 8 
 9             } //end regist the client function
10 
11         } //end of the initfunction

这个时候客户端B接收到消息,用Js的方法显示出来消息. 一次通话就完成了.

 

<------------二,客户端传递参数给服务端并从服务端得到返回值:------------>

前端代码:

 1 <!DOCTYPE html>
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4     <title></title>
 5     <!--Script references. -->
 6     <!--Reference the jQuery library. -->
 7     <script src="Scripts/jquery-1.10.2.min.js"></script>
 8     <!--Reference the SignalR library. -->
 9     <script src="Scripts/jquery.signalR-2.0.2.js"></script>
10     <!--Reference the autogenerated SignalR hub script. -->
11     <script src='signalr/hubs'></script>
12     <!--Add script to update the page and send messages.-->
13     <script type='text/javascript'>
14 
15 
16         $(function () {
17             // Declare a proxy to reference the hub.
18             var chat = $.connection.ViewDataHub;
19 
20 
21             //init the client function 
22             init(chat);
23 
24 
25             $("#btnclick").click(function () {
26                 //Response the information
27                 $.connection.hub.start().done(function () {
28                     chat.server.hello($("#txttalk").val()).done(function (res) {
29                         var talk = "<h1>" + res + "</h1>";
30 
31                         $("#dvtalk").append(talk);
32                     })//end of done function
33                 })//the end of the $.connection
34             })//end of click function
35 
36 
37 
38             $("#btntalk").click(function () {
39                 $.connection.hub.start().done(function () {
40                     chat.server.sendMessag($("#txttalk").val());
41                     $("#txttalk").val("");
42                 })//the end of the $.connection
43 
44             });//btntalk end
45 
46         })
47 
48 
49         //init the client method
50         function init(chat) {
51 
52             chat.client.talk = function (message) {
53                 var talk = "<h1>" + message + "</h1>";
54 
55                 $("#dvtalk").append(talk);
56 
57             } //end regist the client function
58 
59         } //end of the initfunction
60 
61     </script>
62 </head>
63 <body>
64     <div>
65         <table id="tbtoday"></table>
66         <input type="text" id="txttalk" width="150"/>
67         <input type="button" id="btnclick" value="clickme" />
68         <input type="button" id="btntalk" value="talkwithme" />
69         <div id="dvtalk">
70 
71         </div>
72     </div>
73 </body>
74 </html>
View Code

 

后端代码:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using Microsoft.AspNet.SignalR;
 6 using Microsoft.AspNet.SignalR.Hubs;
 7 
 8 namespace SignalRChat.Hubs.Data
 9 {
10     [HubName("ViewDataHub")]
11     public class ViewDataHub : Hub
12     {
13         //this is just called by client and return the value for it .
14         public string Hello(string msg)
15         {
16 
17             string res = "sorry ,i don't know";
18             if (msg.Contains("hello"))
19             {
20                 res = "hello ,guy";
21             }
22             if (msg.Contains("how"))
23             {
24                 res = "how are you ~";
25             }
26             if (msg.Contains("love"))
27             {
28                 res = "don't fall in love with me ~";
29             }
30             return res;
31         }
32 
33 
34 
35         //this fucntion will be called by client and the inside function 
36         //Clients.Others.talk(message);
37         //will be called by clinet javascript function .
38         public void SendMessag(string message)
39         {
40             Clients.Others.talk(message);
41         }
42 
43     }
44 }
View Code

 

效果图:

 

<------------三,客户端刷时时的刷新数据------------> 

前端:

 1 <!DOCTYPE html>
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 5     <title></title>
 6     <script src="Scripts/jquery-1.6.4.min.js"></script>
 7     <script src="Scripts/jquery.signalR-2.2.0.min.js"></script>
 8     <script src='signalr/hubs'></script>
 9     <script>
10         var chat;
11         var arr = [];
12         var loopdo;
13         //
14         $(function () {
15             // Created proxy            
16             chat = $.connection.viewDataHub;
17             Init(chat);
18             //on the start done
19             $.connection.hub.start().done(function () {
20 
21                 $("#btnloop").click(function () {
22                     chat.server.refresh().done(function (data) {
23                         AppendTable(data);
24                     })//done end
25                 }) //btnloop  end
26 
27 
28                 $("#btnclient").click(function () {
29                     chat.server.RefreshClients();
30                 });
31 
32 
33                 $("#btnclick").click(function () {
34                     Start();
35                 });
36 
37 
38                 $("#btnstop").click(function () {
39                     Stop();
40                 });
41 
42             })
43         }) //$function
44 
45 
46         function Start() {
47             if (loopdo == null) {
48                 loopdo = setInterval('$("#btnloop").click()', 1000);
49             }
50 
51         }
52 
53         function Stop() {
54             if (loopdo != null) {
55                 clearInterval(loopdo);
56             }
57         }
58 
59         function AppendTable(data) {
60             arr.length = 0;
61             arr.push("<tr><th>Opendoor</th><th>Price</th><th>Opentiem</th></tr>");
62             $.each(data, function (i) {
63                 arr.push("<tr>");
64                 arr.push("<td>" + data[i].Opendoor + "</td>");
65                 arr.push("<td>" + data[i].Price + "</td>");
66                 arr.push("<td>" + data[i].Opentiem + "</td>");
67                 arr.push("</tr>");
68             });
69             $("#tblist").html(arr.join(""));
70         }
71 
72         function Init(chat) {
73             chat.client.myrefresh = function (data) {
74                 AppendTable(data);
75             }
76 
77         }
78 
79     </script>
80 </head>
81 <body>
82     <input type="button" id="btnclick" value="Start" />
83 
84     <input type="button" id="btnloop" value="View" style="display: none" />
85 
86     <input type="button" id="btnstop" value="Stop" />
87 
88     <input type="button" id="btnclient" value="ClientAll" />
89     <table id="tblist">
90     </table>
91 </body>
92 
93 
94 
95 </html>
View Code

后端:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using Microsoft.AspNet.SignalR;
 6 using Microsoft.AspNet.SignalR.Hubs;
 7 namespace MyReresh.ViewData
 8 {
 9     [HubName("viewDataHub")]
10     public class ViewDataHub : Hub
11     {
12         [HubMethodName("refresh")]
13         public List<Stock> Refresh()
14         {
15             return Stock.GetAll();
16         }
17 
18         [HubMethodName("RefreshClients")]
19         public void RefreshClients()
20         {
21             Clients.All.myrefresh(Stock.GetAll());
22         }
23 
24 
25     }
26 
27     public class Stock
28     {
29         private string opendoor;
30 
31         public string Opendoor
32         {
33             get { return opendoor; }
34             set { opendoor = value; }
35         }
36 
37         private double price;
38 
39         public double Price
40         {
41             get { return price; }
42             set { price = value; }
43         }
44 
45         private DateTime opentiem = System.DateTime.Now;
46 
47         public DateTime Opentiem
48         {
49             get { return opentiem; }
50             set { opentiem = value; }
51         }
52 
53 
54         public static List<Stock> GetAll()
55         {
56             Random rand = new Random();
57             List<Stock> list = new List<Stock>() 
58             {
59                 new Stock{Opendoor="Door1",Price=rand.NextDouble()*100},
60                 new Stock{Opendoor="Door2",Price=rand.NextDouble()*100},
61                 new Stock{Opendoor="Door3",Price=rand.NextDouble()*100}
62             };
63             return list;
64         }
65 
66     }
67 }
View Code

 

注:本次实现的所谓的时时刷新数据和官方提供的Demo有很大的差异,并不是后台代码的角度来刷新,而是从前端的角度来实现的。

 

====>点我下载DEMO<====

posted @ 2015-03-30 22:46  爱吃猫的鱼  阅读(6978)  评论(27编辑  收藏  举报