Overview

This tutorial introduces SignalR development by showing how to build a simple browser-based chat application.  You will add the SignalR library to an empty ASP.NET web application, create a hub class for sending messages to clients, and create an HTML page that lets users send and receive chat messages. For a similar tutorial that shows how to create a chat application in MVC 4 using an MVC view, see Getting Started with SignalR and MVC 4.

Note: This tutorial uses the release (1.x) version of SignalR.  For details on changes between SignalR 1.x and 2.0, see Upgrading SignalR 1.x Projects.

SignalR is an open-source .NET library for building web applications that require live user interaction or real-time data updates.  Examples include social applications, multiuser games, business collaboration, and news, weather, or  financial update applications. These are often called real-time applications.

SignalR simplifies the process of building real-time applications.  It includes an ASP.NET server library and a JavaScript client library to make it easier to manage client-server connections and push content updates to clients. You can add the SignalR library to an existing ASP.NET application to gain real-time functionality.

The tutorial demonstrates the following SignalR development tasks:

  • Adding the SignalR library to an ASP.NET web application.
  • Creating a hub class to push content to clients.
  • Using the SignalR jQuery library in a web page to send messages and display updates from the hub.

The following screen shot shows the chat application running in a browser. Each new user can post comments and see comments added after the user joins the chat.

Sections:

Set up the Project

This section shows how to create an empty ASP.NET web application, add SignalR, and create the chat application.

Prerequisites:

  • Visual Studio 2010 SP1 or 2012.  If you do not have Visual Studio, see ASP.NET Downloads to get the free Visual Studio 2012 Express Development Tool.
  • Microsoft ASP.NET and Web Tools 2012.2. For Visual Studio 2012, this installer adds new ASP.NET features including SignalR templates to Visual Studio.  For Visual Studio 2010 SP1, an installer is not available but you can complete the tutorial by installing the SignalR NuGet package as described in the setup steps.

The following steps use Visual Studio 2012 to create an ASP.NET Empty Web Application and add the SignalR library:

  1. In Visual Studio create an ASP.NET Empty Web Application.

  2. In Solution Explorer, right-click the project, select Add | New Item, and select the SignalR Hub Class item.  Name the class ChatHub.cs and add it to the project.  This step creates the ChatHub class and adds to the project a set of script files and assembly references that support SignalR.

    Note: You can also add SignalR to a project by opening the Tools | Library Package Manager | Package Manager Console and running a command: install-packageMicrosoft.AspNet.SignalR.  If you use the console to add SignalR, create the SignalR hub class as a separate step after you add SignalR.

  3. In Solution Explorer expand the Scripts node. Script libraries for jQuery and SignalR are visible in the project.

  4. Replace the code in the new ChatHub class with the following code.

    usingSystem;usingSystem.Web;usingMicrosoft.AspNet.SignalR;namespaceSignalRChat{publicclassChatHub:Hub{publicvoidSend(string name,string message){// Call the broadcastMessage method to update clients.Clients.All.broadcastMessage(name, message);}}}
  5. In Solution Explorer, right-click the project, then click Add | New Item. In the Add New Item dialog, select Global Application Class and click Add.

  6. Add the following using statements after the provided using statements in the Global.asax.cs class.

    usingSystem.Web.Routing;usingMicrosoft.AspNet.SignalR;
  7. Add the following line of code in the Application_Start method of the Global class to register the default route for SignalR hubs.

    // Register the default hubs route: ~/signalr/hubsRouteTable.Routes.MapHubs();
  8. In Solution Explorer, right-click the project, then click Add | New Item. In the Add New Item dialog, select Html Page and click Add.

  9. In Solution Explorer, right-click the HTML page you just created and click Set as Start Page.

  10. Replace the default code in the HTML page with the following code.

    <!DOCTYPE html><html><head><title>SignalR Simple Chat</title><styletype="text/css">.container {background-color:#99CCFF;border: thick solid #808080;padding:20px;margin:20px;}</style></head><body><divclass="container"><inputtype="text"id="message"/><inputtype="button"id="sendmessage"value="Send"/><inputtype="hidden"id="displayname"/><ulid="discussion"></ul></div><!--Script references. --><!--Reference the jQuery library. --><scriptsrc="/Scripts/jquery-1.8.2.min.js"></script><!--Reference the SignalR library. --><scriptsrc="/Scripts/jquery.signalR-1.0.0.js"></script><!--Reference the autogenerated SignalR hub script. --><scriptsrc="/signalr/hubs"></script><!--Add script to update the page and send messages.--><scripttype="text/javascript">
    $(function(){// Declare a proxy to reference the hub. var chat = $.connection.chatHub;// Create a function that the hub can call to broadcast messages.
    chat.client.broadcastMessage =function(name, message){// Html encode display name and message. var encodedName = $('<div />').text(name).html();var encodedMsg = $('<div />').text(message).html();// Add the message to the page.
    $('#discussion').append('<li><strong>'+ encodedName
    +'</strong>:&nbsp;&nbsp;'+ encodedMsg +'</li>');};// Get the user name and store it to prepend to messages.
    $('#displayname').val(prompt('Enter your name:',''));// Set initial focus to message input box.
    $('#message').focus();// Start the connection.
    $.connection.hub.start().done(function(){
    $('#sendmessage').click(function(){// Call the Send method on the hub.
    chat.server.send($('#displayname').val(), $('#message').val());// Clear text box and reset focus for next comment.
    $('#message').val('').focus();});});});</script></body></html>
  11. Save All for the project.

Run the Sample

  1. Press F5 to run the project in debug mode. The HTML page loads in a browser instance and prompts for a user name.

  2. Enter a user name.

  3. Copy the URL from the address line of the browser and use it to open two more browser instances. In each browser instance, enter a unique user name.
  4. In each browser instance, add a comment and click Send. The comments should display in all browser instances.

    Note: This simple chat application does not maintain the discussion context on the server. The hub broadcasts  comments to all current users. Users who join the chat later will see messages added from the time they join.

    The following screen shot shows the chat application running in three browser instances, all of which are updated  when one instance sends a message:

  5. In Solution Explorer, inspect the Script Documents node for the running application. There is a script file named hubs that the SignalR library dynamically generates at runtime. This file manages the communication between jQuery script and server-side code.

Examine the Code

The SignalR chat application demonstrates two basic SignalR development tasks:  creating a hub as the main coordination object on the server, and using the SignalR jQuery library to send and receive messages.

SignalR Hubs

In the code sample the ChatHub class derives from the Microsoft.AspNet.SignalR.Hub class. Deriving from the Hub class is a useful way to build a SignalR application.  You can create public methods on your hub class and then access those methods by calling them from jQuery scripts in a web page.

In the chat code, clients call the ChatHub.Send method to send a new message.  The hub in turn sends the message to all clients by calling Clients.All.broadcastMessage.

The Send method demonstrates several hub concepts :

  • Declare public methods on a hub so that clients can call them.
  • Use the Microsoft.AspNet.SignalR.Hub.Clients dynamic property to access all clients connected to this hub.
  • Call a jQuery function on the client (such as the broadcastMessage function) to update clients.

    publicclassChatHub:Hub{publicvoidSend(string name,string message){// Call the broadcastMessage method to update clients.Clients.All.broadcastMessage(name, message);}}

SignalR and jQuery

The HTML page in the code sample shows how to use the SignalR jQuery library to communicate with a SignalR hub. The essential tasks in the code are declaring a proxy to reference the hub, declaring a function that the server can call to push content to clients, and starting a connection to send messages to the hub.

The following code declares a proxy for a hub.

var chat = $.connection.chatHub;

Note: In jQuery the reference to the server class and its members is in camel case.  The code sample references the C# ChatHub class in jQuery as chatHub.

The following code is how you create a callback function in the script.  The hub class on the server calls this function to push content updates to each client. The two lines that HTML encode the content before displaying it are optional and show a simple way to prevent script injection.

    chat.client.broadcastMessage =function(name, message){// Html encode display name and message. var encodedName = $('<div />').text(name).html();var encodedMsg = $('<div />').text(message).html();// Add the message to the page.
$('#discussion').append('<li><strong>'+ encodedName
+'</strong>:&nbsp;&nbsp;'+ encodedMsg +'</li>');};

The following code shows how to open a connection with the hub. The code starts the connection and then passes it a function to handle the click event on the Send button in the HTML page.

Note: This approach insures that the connection is established before the event handler executes.

    $.connection.hub.start().done(function(){
$('#sendmessage').click(function(){// Call the Send method on the hub.
chat.server.send($('#displayname').val(), $('#message').val());// Clear text box and reset focus for next comment.
$('#message').val('').focus();});});

Next Steps

You learned that SignalR is a framework for building real-time web applications.  You also learned several SignalR development tasks: how to add SignalR to an ASP.NET application, how to create a hub class, and how to send and receive messages from the hub.

You can make the sample application in this tutorial or other SignalR applications available over the Internet by deploying them to a hosting provider. Microsoft offers free web hosting for up to 10 web sites in a free Windows Azure trial account. For a walkthrough on how to deploy the sample SignalR application, see Publish the SignalR Getting Started Sample as a Windows Azure Web Site. For detailed information about how to deploy a Visual Studio web project to a Windows Azure Web Site, see Deploying an ASP.NET Application to a Windows Azure Web Site. (Note: The WebSocket transport is not currently supported for Windows Azure Web Sites.  When WebSocket transport is not available, SignalR uses the other available transports as described in the Transports section of the Introduction to SignalR topic.)

To learn more advanced SignalR developments concepts, visit the following sites for SignalR source code and resources:

Tutorial: Getting Started with SignalR (C#) -摘自网络的更多相关文章

  1. Android:控件WebView显示网页 -摘自网络

    WebView可以使得网页轻松的内嵌到app里,还可以直接跟js相互调用. webview有两个方法:setWebChromeClient 和 setWebClient setWebClient:主要 ...

  2. C# 中的内存管理,摘自网络

    C#编程的一个优点是程序员不需要关心具体的内存管理,尤其是垃圾收集器会处理所有的内存清理工作.虽然不必手工管理内存,但如果要编写高质量的代码,还是要理解后台发生的事情,理解C#的内存管理.本文主要介绍 ...

  3. Ubuntu的常用快捷键(摘自网络)

    篇一 : Ubuntu的复制粘贴操作及常用快捷键(摘自网络) Ubuntu的复制粘贴操作 1.最为简单,最为常用的应该是鼠标右键操作了,可以选中文件,字符等,右键鼠标,复制,到目的地右键鼠标,粘贴就结 ...

  4. Introduction to SignalR -摘自网络

    What is SignalR? ASP.NET SignalR is a library for ASP.NET developers that simplifies the process of ...

  5. SignalR Supported Platforms -摘自网络

    SignalR is supported under a variety of server and client configurations. In addition, each transpor ...

  6. 理解OAuth 2.0 -摘自网络

    OAuth是一个关于授权(authorization)的开放网络标准,在全世界得到广泛应用,目前的版本是2.0版.                                      本文对OA ...

  7. 部署 外网 ASP.NET程序时, IIS安全性 配置 -摘自网络

    最近,和朋友们在聊及ASP.NET程序的安全性没有JAVA高,IIS(Internet Infomartion Server)的存在很多漏洞(以及新型蠕虫,例如Code Red 和Nimda),安全得 ...

  8. 【摘自网络】陈奕迅&&杨千嬅

    揭陈奕迅杨千嬅相爱18年恋人未满的点滴片段 文/一床情书 但凡未得到,但凡是过去,总是最登对 ——题记 已经仙逝多年的香港歌坛天后梅艳芳曾经在<似是故人来>里唱道:“但凡未得到,但凡是过去 ...

  9. mongoDB 3.0 安全权限访问控制 -摘自网络

    "E:\Program Files\MongoDB\Server\3.0\bin\mongod.exe" --logpath E:\mongodb\log\mongodblog.l ...

随机推荐

  1. 批量将MP4 转换为 MP3

    0 需要先下载VLC 软件 1 win+R 运行 "CMD" 2 CD mp4目录 3 复制 并运行下面代码 for %%a in (*.mp4) do "C:\Prog ...

  2. SQL Server 修改排序规则

    Net stop mssqlserver Setup /QUIET /ACTION=REBUILDDATABASE /instancename=mssqlserver /SQLSYSADMINACCO ...

  3. SQL2008附加数据库提示错误:5120

    前几天在附加数据库时,出现了这个错误           在win7 x64系统上使用sql2008进行附加数据库(包括在x86系统正在使用的数据库文件,直接拷贝附加在X64系统中)时,提示无法打开文 ...

  4. [转载]MongoDB 常用命令

    mongodb由C++编写,其名字来自humongous这个单词的中间部分,从名字可见其野心所在就是海量数据的处理.关于它的一个最简洁描述为:scalable, high-performance, o ...

  5. Firefly 性能测试 报告

    原地址:http://bbs.gameres.com/thread_223724.html Firefly 性能测试 主要考虑点 网络IO的并发 进程间通信压力 数据读写压力 测试机配置: 操作系统 ...

  6. android 自定义按钮的外边框

    <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http: ...

  7. Jmeter使用——参数化

    最近一个想项目使用jmeter进行测试,陆续将遇到并解决的问题记录下来,本次主要记录参数化得一些问题. 1. 单台压力机 多个线程组不重复数字,注意分布式负载时多个压力机会出现重复的问题 主要思路分别 ...

  8. linux 匹配查询列表中包含某一特殊字符的所有行中的某一列

    命令: ll | grep sh | awk '{print $9}' 解析: 其中,匹配列的命令为awk '{print $n}',$n为匹配的第几列.

  9. java比较器Comparable接口和Comaprator接口

    Comparable故名思意是比较,意思就是做比较的,然后进行排序. 1.什么是comparable接口 此接口强行对实现它的每个类的对象进行整体排序.此排序被称为该类的自然排序 ,类的 compar ...

  10. 【HDOJ】2065 "红色病毒"问题

    刚开始看这道题目的时候,完全没看出来是递推.看了网上大牛的分析.立刻就明白了.其实无论字符串长度为多少,都可以将该长度下的组合分成四种情况S1(A偶数C偶数).S2(A偶数C奇数).S3(A奇数C偶数 ...