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

最全的参考:http://www.asp.net/signalr/overview/getting-started

关于如果安装SignalR: NuGet命令:

PM> Install-Package Microsoft.AspNet.SignalR

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

后台代码示例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
namespace SignalRChat.Hubs.Data
{
  [HubName("ViewDataHub")]
  public class ViewDataHub : Hub
  {
    //this is just called by client and return the value for it .
    public string Hello()
    {
      return "hello";
    }
    //this fucntion will be called by client and the inside function
    //Clients.Others.talk(message);
    //will be called by clinet javascript function .
    public void SendMessag(string message)
    {
      Clients.Others.talk(message);
    }
  }
}

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

前台代码示例:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title></title>
  <!--Script references. -->
  <!--Reference the jQuery library. -->
  <script src="Scripts/jquery-1.10.2.min.js"></script>
  <!--Reference the SignalR library. -->
  <script src="Scripts/jquery.signalR-2.0.2.js"></script>
  <!--Reference the autogenerated SignalR hub script. -->
  <script src='signalr/hubs'></script>
  <!--Add script to update the page and send messages.-->
  <script type='text/javascript'>
    $(function () {
      // Declare a proxy to reference the hub.
      var chat = $.connection.ViewDataHub;
      //init the client function
      init(chat);
      $("#btnclick").click(function () {
        //Response the information
        $.connection.hub.start().done(function () {
          chat.server.hello().done(function (res) {
            alert(res);
          })//end of done function
        })//the end of the $.connection
      })//end of click function
      $("#btntalk").click(function () {
        $.connection.hub.start().done(function () {
          chat.server.sendMessag($("#txttalk").val());
          $("#txttalk").val("");
        })//the end of the $.connection
      });//btntalk end
    })
    //init the client method
    function init(chat) {
      chat.client.talk = function (message) {
        var talk = "<h1>" + message + "</h1>";
        $("#dvtalk").append(talk);
      } //end regist the client function
    } //end of the initfunction
  </script>
</head>
<body>
  <div>
    <table id="tbtoday"></table>
    <input type="text" id="txttalk" width="150"/>
    <input type="button" id="btnclick" value="clickme" />
    <input type="button" id="btntalk" value="talkwithme" />
    <div id="dvtalk">
    </div>
  </div>
</body>
</html>

出现的效果:

两个窗口之间的聊天

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

客户端A发送信息->服务端接收->服务端Post消息给客户端B

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

$("#btntalk").click(function () {
                $.connection.hub.start().done(function () {
                    chat.server.sendMessag($("#txttalk").val());
                    $("#txttalk").val("");
                })//the end of the $.connection

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

后端代码:

 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 }

效果图:

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

前端:

 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>

后端:

 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 }

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

更多学习资料:www.javarecord.com

不用找了,比较全的signalR例子已经为你准备好了.的更多相关文章

  1. 不用找了,比较全的signalR例子已经为你准备好了(2)---JqGrid 服务端刷新方式-注释详细-DEMO源码下载

    上次用客户端进行数据刷新的方式,和官方的Demo实现存在差异性,今天花了一点时间好好研究了一下后台时时刷新的方式.将写的代码重新update了一次,在这之前找过好多的资料,发现都没有找到好的例子,自己 ...

  2. signalR例子

    不用找了,比较全的signalR例子已经为你准备好了.   这几天想着将一个winform的工具上线到web上,因为对时时性的要求比较高,找朋友咨询了一下推荐了SignlarR 框架,比较强大.昨天才 ...

  3. 史上最全面的SignalR系列教程-2、SignalR 实现推送功能-永久连接类实现方式

    1.概述 通过上篇史上最全面的SignalR系列教程-1.认识SignalR文章的介绍,我们对SignalR技术已经有了一个全面的了解.本篇开始就通过SignalR的典型应用的实现方式做介绍,例子虽然 ...

  4. 史上最全面的SignalR系列教程-4、SignalR 自托管全解(使用Self-Host)-附各终端详细实例

    1.概述 通过前面几篇文章 史上最全面的SignalR系列教程-1.认识SignalR 史上最全面的SignalR系列教程-2.SignalR 实现推送功能-永久连接类实现方式 史上最全面的Signa ...

  5. 史上最全面的SignalR系列教程-5、SignalR 实现一对一聊天

    1.概述 通过前面几篇文章 史上最全面的SignalR系列教程-1.认识SignalR 史上最全面的SignalR系列教程-2.SignalR 实现推送功能-永久连接类实现方式 史上最全面的Signa ...

  6. “摆地摊“都找不到全栈工程师?JNPF帮你分分钟搞定!

    大街上捕捉野生程序员 都这样了还找不到全栈工程师 全栈工程师(Full-Stack Engineer)图鉴: 全栈工程师,也叫全端工程师(同时具备前端和后台能力),英文Full Stack  deve ...

  7. 史上最全面的SignalR系列教程-3、SignalR 实现推送功能-集线器类实现方式

    1.概述 通过前两篇 史上最全面的SignalR系列教程-1.认识SignalR 史上最全面的SignalR系列教程-2.SignalR 实现推送功能-永久连接类实现方式 文章对SignalR的介绍, ...

  8. 史上最全面的SignalR系列教程-6、SignalR 实现聊天室

    1.概述 通过前面几篇文章对SignalR的详细介绍.我们知道Asp.net SignalR是微软为实现实时通信的一个类库.一般情况下,SignalR会使用JavaScript的长轮询(long po ...

  9. 史上最全面的SignalR系列教程-目录汇总

    1.引言 最遗憾的不是把理想丢在路上,而是理想从未上路. 每一个将想法变成现实的人,都值得称赞和学习. 致正在奔跑的您! 2.SignalR介绍 SignalR实现服务器与客户端的实时通信 ,她是一个 ...

随机推荐

  1. Java高级--Java线程运行栈信息的获取 getStackTrace()

    我们在Java程序中使用日志功能(JDK Log或者Log4J)的时候,会发现Log系统会自动帮我们打印出丰富的信息,格式一般如下:为了免去解析StackTrace字符串的麻烦,JDK1.4引入了一个 ...

  2. 监听器 listener 样例

    1. 在web.xml 添加 <listener>    <listener-class>listener.TestListener</listener-class> ...

  3. android81 多线程下载和断电续传

    package com.itheima.multithreaddownload; import java.io.BufferedReader; import java.io.File; import ...

  4. linux下64位汇编的系统调用系列

    http://blog.csdn.net/mydo/article/category/3084893

  5. Eclipse Key Shortcuts for Greater Developers Productivity--reference

    Posted by Ajitesh Kumar / In Java / June 6, 2014 http://vitalflux.com/eclipse-key-shortcuts-greater- ...

  6. microchip PIC芯片使用方法

    pickit3调试器使用: http://www.eeboard.com/evaluation/pickit3debug/1/ MPLAB环境使用: 1.代码折叠功能 2.代码补全功能 3.函数跳转功 ...

  7. 【锋利的jQuery】学习笔记04

    第四章 jQuery中的事件和动画 一.jQuery中的事件 加载DOM 在JS中等待页面加载完成通常使用window.onload方法,而在jQuery中则使用$(document).ready() ...

  8. [Excel] C#DataToExcel帮助类 (转载)

    点击下载 DataToExcel.rar 看下面代码吧 /// <summary> /// 类说明:DataToExcel /// 编 码 人:苏飞 /// 联系方式:361983679 ...

  9. oracle数据库的导出与导入

    导出:exp devtest10/dev10@172.16.7.39:1521/WSRZ file=d:\WSRZ.dmp log=d:\WSRZ.log full=y 导入:imp testdb/t ...

  10. map函数(转)

    STL中map用法详解 说明:如果你具备一定的C++ template知识,即使你没有接触过STL,这个文章你也应该可能较轻易的看懂.本人水平有限,不当之处,望大家辅正. 一.Map概述 Map是ST ...