原文地址:

What is SignalR and why should I use it?

When I first heard about SignalR, I was not sure what was the point of it. The official description says that SignalR is a library that can be used with any ASP.NET application to add real-time communication. But since what they meant by real-time was not totally clear to me, and the only example was a chat room, I pushed it aside for a while.

When I started to work on my side project, I also started thinking about SignalR again. One of the things I want to do was refresh the schedule as soon as a change was made: if a user makes a modification, it should be visible to all other users. The classic way to do something like that would be to call the server at regular intervals to get the status of the schedule, but to have pseudo real-time update, you must call the server pretty often.

With SignalR, the server can call a JavaScript methods on all the clients by itself when updates are required. The library will handle the connection needed to achieve this: by default WebSocket is used, but it will fallback automatically to older connections types if WebSocket is not available in the browser. The JavaScript can also call the server: this can already be done with AJAX, but if two-way communication is needed it may be easier and cleaner to do it all with SignalR.

So, using a real-time library is the way to go if you want to build an application that requires collaboration between users. Common uses cases includes editors, social networks, chats or a schedule like my project.

Getting started with SignalR is pretty simple. Here is an example with my side project: sessions for an event can be modified by any user, and when a session is modified the change is visible for all the user currently logged in the application.

On the Server

First, you must add the Microsoft ASP.NET SignalR package to your ASP.NET application using NuGet, along with the jQuery package if you don’t already have it.

After this, you must create a class that derives from the Hub class. All the methods of the hub can be called from JavaScript. Also, those methods can call JavaScript methods on the client.

Hide Copy Code

namespace EventScheduling
{
public class SessionsHub : Hub
{
public void SessionModified(ScheduledSession scheduledSession)
{
// Call the JavaScript method sendSessionChanged on all the clients
Clients.All.sendSessionChanged(scheduledSession);
}
}
}

To enable communications between the hub and the JavaScript, you must also enable SignalR in the Configuration method in the Startup class of your application.

Hide Copy Code

namespace EventScheduling
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
}

On the Client

On the client, you must include the jquery.signalR-2.2.0.js file containing the JavaScript for the SignalR library and the package ~/signalr/hubs. This package is automatically generated from your Hub classes and contains all the JavaScript required to call the server and receive message from the server.

Hide Copy Code

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

After this, when the page is loaded and ready, you must declare the JavaScript function called by the server-side code. Since the Hub class is called SessionsHub and the SessionModified method of the hub class calls the sendSessionChanged method, this function must be declared in the $.connection.sessionsHub.client.sendSessionChanged variable.

Once this function is created, you must also connect to the hubs using the $.connection.hub.start method. You can also add initialization code in the done() callback which will be called when the connection is started.

Hide Copy Code

$(document).ready(function () {
// Create a function that the hub can call to broadcast messages.
$.connection.sessionsHub.client.sendSessionChanged = function (session) {
// Display the session again using the new data received from the server
});
}; // Start the connection and create a function that the hub will call when loaded
$.connection.hub.start().done($("#Sessions").on("click", ".Session", function (event) {
var that = $(this);
var currentSession = that.data("session");
currentSession.Title = currentSession.Title + "Clicked";
// Call the server, which will notify all clients of the change in the title
$.connection.sessionsHub.server.sessionModified(currentSession);
}));
});

In the example, when the hubs are done starting, a click handler is added to each session on the page. When the users clicks a session, the word Clicked is added to the title of that session, and all browsers showing the page are notified. Since the SessionModified method was declared in the SessionsHub class of the server, it can be called from JavaScript using the $.connection.sessionsHub.server.sessionModified method.

With only this small bit of code, you now have two-way communications between the client and the server, which you can use to update data in real-time for your users. I will use SignalR in future projects, that’s for sure!

What is SignalR and Why Should I Use It?的更多相关文章

  1. SignalR系列续集[系列8:SignalR的性能监测与服务器的负载测试]

    目录 SignalR系列目录 前言 也是好久没写博客了,近期确实很忙,嗯..几个项目..头要炸..今天忙里偷闲.继续我们的小系列.. 先谢谢大家的支持.. 我们来聊聊SignalR的性能监测与服务器的 ...

  2. ABP文档 - SignalR 集成

    文档目录 本节内容: 简介 安装 服务端 客户端 连接确立 内置功能 通知 在线客户端 帕斯卡 vs 骆峰式 你的SignalR代码 简介 使用Abp.Web.SignalR nuget包,使基于应用 ...

  3. SignalR快速入门 ~ 仿QQ即时聊天,消息推送,单聊,群聊,多群公聊(基础=》提升)

     SignalR快速入门 ~ 仿QQ即时聊天,消息推送,单聊,群聊,多群公聊(基础=>提升,5个Demo贯彻全篇,感兴趣的玩才是真的学) 官方demo:http://www.asp.net/si ...

  4. SignalR代理对象异常:Uncaught TypeError: Cannot read property 'client' of undefined 推出的结论

    异常汇总:http://www.cnblogs.com/dunitian/p/4523006.html#signalR 后台创建了一个DntHub的集线器 前台在调用的时候出现了问题(经检查是代理对象 ...

  5. 基于SignalR实现B/S系统对windows服务运行状态的监测

    通常来讲一个BS项目肯定不止单独的一个BS应用,可能涉及到很多后台服务来支持BS的运行,特别是针对耗时较长的某些任务来说,Windows服务肯定是必不可少的,我们还需要利用B/S与windows服务进 ...

  6. SignalR SelfHost实时消息,集成到web中,实现服务器消息推送

    先前用过两次SignalR,但是中途有段时间没弄了,今天重新弄,发现已经忘得差不多了,做个笔记! 首先创建一个控制台项目Nuget添加引用联机搜索:Microsoft.AspNet.SignalR.S ...

  7. SignalR系列目录

    [置顶]用SignalR 2.0开发客服系统[系列1:实现群发通讯] [置顶]用SignalR 2.0开发客服系统[系列2:实现聊天室] [置顶]用SignalR 2.0开发客服系统[系列3:实现点对 ...

  8. 基于SignalR的消息推送与二维码描登录实现

    1 概要说明 使用微信扫描登录相信大家都不会陌生吧,二维码与手机结合产生了不同应用场景,基于二维码的应用更是比较广泛.为了满足ios.android客户端与web短信平台的结合,特开发了基于Singl ...

  9. XAMARIN.ANDROID SIGNALR 实时消息接收发送示例

    SignalR 是一个开发实时 Web 应用的 .NET 类库,使用 SignalR 可以很容易的构建基于 ASP.NET 的实时 Web 应用.SignalR 支持多种服务器和客户端,可以 Host ...

  10. ABP源码分析三十二:ABP.SignalR

    Realtime Realtime是ABP底层模块提供的功能,用于管理在线用户.它是使用SignalR实现给在线用户发送通知的功能的前提 IOnlineClient/OnlineClient: 封装在 ...

随机推荐

  1. 0118——UILabel和导入字体

    UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(10, 100, 300, 100)]; 1.设置文字颜色 label.textC ...

  2. iOS nav加角标

    写一个类别加上就可以啦 #import "UIBarButtonItem+Badge.h" #import "BadgeView.h" #import < ...

  3. 简单的拖动手势控制侧拉view显示

    通过 UIPanGestureRecognizer  手势来控制侧拉view的显示 在QHLViewController.m文件中,先添加一些宏定义和参数等等. #define QHLAnimatin ...

  4. POJ 2140 Herd Sums

    http://poj.org/problem?id=2140 Description The cows in farmer John's herd are numbered and branded w ...

  5. mac terminal的使用技巧

    1. 多tab支持    1)terminal y也是支持多tab的, Cmd+T可以打开一个新的tab    2) cmd + shift + { / } 可以在tab间切换   2. termia ...

  6. Redis 入门之编译安装

    Redis是一个开源的使用ANSI C语言编写.支持网络.可基于内存亦可持久化的日志型.Key-Value数据库,并提供多种语言的API.从2010年3月15日起,Redis的开发工作由VMware主 ...

  7. mysql之7xtrabackup

    目录: 1.前言 2.环境 3.开始备份 3.1.innobackupex介绍 3.2.一次完全备份 3.3.一次完全恢复 3.4.增量备份 3.5.增量备份的恢复过程 1.前言: Xtrabacku ...

  8. linux软件安装(rpm,源码编译)

    1.rpm(redhat package manager)管理器主要目的在于解决软件的安装.卸载.升级.查询.验证等,例如升级过程中,保留软件的配置文件,安装过程中,检查软件依赖的库文件,以及卸载过程 ...

  9. [XMPP]iOS聊天软件学习笔记[二]

    @import url(http://i.cnblogs.com/Load.ashx?type=style&file=SyntaxHighlighter.css);@import url(/c ...

  10. tomcat那些事

    Tomcat7.0.22安装配置 1.下载tomcat7.0.22  下载地址:http://tomcat.apache.org/download-70.cgi 2.添加系统环境变量,我的电脑-> ...