这几天想着将一个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. PPT内嵌视频(指发布时只需要ppt一个文件即可)

    做实验时用手机拍了视频,想把视频嵌入到PPT中.只是单纯的嵌入很容易,但是我想将PPT推送给其他人时,不需要再传视频文件.搜了一下做法,可以通过flash视频格式实现.电脑为thinkpad笔记本,w ...

  2. Java异常处理面试题归纳

    1.error和exception有什么差别 error表示系统级的错误,是java执行环境内部错误或者硬件问题,不能指望程序来处理这种问题,除了退出执行外别无选择.它是Java虚拟机抛出的. exc ...

  3. pip安装 MySQLDb 和 Django

    wget "https://pypi.python.org/packages/source/p/pip/pip-1.5.4.tar.gz#md5=834b2904f92d46aaa33326 ...

  4. mysql中enum的用法

    字段 类型 长度/值*1 整理 属性 Null 默认2 额外 注释 enum         说明:enum类型的字段,若长度值写长度1/2,报错 (1)  数据长度为1,则为0,1,2… (2)   ...

  5. GUI之CCControlExtension

    Introduction CCControl is inspired by the UIControl API class from the UIKit library of CocoaTouch. ...

  6. AWVS介绍

    使用AWVS对域名进行全局分析,深入探索: 首先,介绍一下AWVS这个工具. Acunetix Web Vulnerability Scanner(简称AWVS)是一款知名的网络漏洞扫描工具,它通过网 ...

  7. linux中的网络通信指令 分类: 学习笔记 linux ubuntu 2015-07-06 16:02 134人阅读 评论(0) 收藏

    1.write write命令通信是一对一的通信,即两个人之间的通信,如上图. 效果图 用法:write <用户名> 2.wall wall指令可将信息发送给每位同意接收公众信息的终端机用 ...

  8. HTML+CSS基础学习笔记(4)

    一.认识CSS样式 1.定义 CSS全称:层叠样式表(Cascading Style Sheets) 主要作用:定义HTML内容在浏览器内的显示样式,比如文字大小.颜色.字体加粗等 优点:通过定义某个 ...

  9. 简洁JS 日历控件 支持日期和月份选择

    原文出处 以下这个JS日历控件是我的闲暇之余自己编写的,所有的代码全部在IE7/IE8/Firefox下面测试通过, 而且可以解决被iframe层遮盖的问题.现在只提供两种风格(简洁版和古典版)和两种 ...

  10. Java-hibernate的Hello World

     hibernate 是对jdbc进行轻量级封装的  orm 框架,充当项目的持久层. 要使用 hibernate首先就需要继续配置, 引包:下载hibernate然后加入jar包 同时引入mysql ...