原文地址:

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. Ext树控件第一次勾选父节点子节点没选中

    项目中同事提出了这样一个bug 问题: 第一次勾选父节点子节点竟然没选中,逆天了啊 初步分析: 可能是之前代码的逻辑错误造成的,随进入调试阶段... 调试中发现该参数为空(原来写代码的也太没素质了), ...

  2. Java坑一

    public class Test { public static void main(String[] args) { Integer a = 12; Integer b = 12; System. ...

  3. (原)vs2013编译成静态库

    转载请注明出处: http://www.cnblogs.com/darkknightzh/p/5477664.html 1. 在“属性”-“配置属性”-“常规”-“配置类型”里面设置“静态库(.lib ...

  4. 【Nutch2.2.1基础教程之2.1】集成Nutch/Hbase/Solr构建搜索引擎之一:安装及运行【单机环境】

    1.下载相关软件,并解压 版本号如下: (1)apache-nutch-2.2.1 (2) hbase-0.90.4 (3)solr-4.9.0 并解压至/usr/search 2.Nutch的配置 ...

  5. ZendFramework2 源码分析 index.php

    <?php /** * This makes our life easier when dealing with paths. Everything is relative * to the a ...

  6. flash播放器遮挡页面中元素问题解决

    今天在做一个包含Flash播放器的页面弹出效果时发现Flash播放器总是跑到页面最上层,发现这个问题与Flash的”wmode”属性有关,至于该元素详细此处不做记录,解决办法如下: IE:加入参数:& ...

  7. 在Docker上部署使用Azure CLI镜像

    Docker是非常流行的容器技术,在Docker中安装部署多种工具非常快速和方便:而Azure CLI是微软提供的可以在Linux/Mac上运行的跨平台命令行管理工具,本文介绍如何在Azure上安装部 ...

  8. Can't create/write to file '/tmp/#sql_3105_0.MYI' (Errcode: 13)

    最近的项目中由于临时存储空间太大了.索性把tmp目录删除了.结果访问出现 Can't create/write to file '/tmp/#sql_3105_0.MYI' (Errcode: 13) ...

  9. webService设置超时时间

    在客户端配置文件中设置: <bindings>      <basicHttpBinding>        <binding name="UrlCrawler ...

  10. window7下statsvn统计代码量

    下载statsvn:http://www.statsvn.org/ 将下载后的statsvn.jar放到d:\svn目录下; 打开cmd窗口切换到需要统计代码的项目目录如:d:\project\web ...