SingalR--demo
原文链接 : http://www.asp.net/signalr/overview/getting-started/tutorial-getting-started-with-signalr-and-mvc
中文链接: http://www.cnblogs.com/humble/p/3857900.html
官方demo下载地址: demo下载
原文粘个过来,方便查询
This tutorial shows how to use ASP.NET SignalR 2 to create a real-time chat application. You will add SignalR to an MVC 5 application and create a chat view to send and display messages.
Software versions used in the tutorial
Using Visual Studio 2012 with this tutorial
Tutorial Versions
Questions and comments
Overview
This tutorial introduces you to real-time web application development with ASP.NET SignalR 2 and ASP.NET MVC 5. The tutorial uses the same chat application code as the SignalR Getting Started tutorial, but shows how to add it to an MVC 5 application.
In this topic you will learn the following SignalR development tasks:
- Adding the SignalR library to an MVC 5 application.
- Creating hub and OWIN startup classes 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 completed chat application running in a browser.
Sections:
Set up the Project
Prerequisites:
- Visual Studio 2013. If you do not have Visual Studio, see ASP.NET Downloads to get the free Visual Studio 2013 Express Development Tool.
This section shows how to create an ASP.NET MVC 5 application, add the SignalR library, and create the chat application.
In Visual Studio, create a C# ASP.NET application that targets .NET Framework 4.5, name it SignalRChat, and click OK.
In the
New ASP.NET Project
dialog, and select MVC, and click Change Authentication.Select No Authentication in the Change Authentication dialog, and click OK.
Note: If you select a different authentication provider for your application, a
Startup.cs
class will be created for you; you will not need to create your ownStartup.cs
class in step 10 below.Click OK in the New ASP.NET Project dialog.
Open the Tools | Library Package Manager | Package Manager Console and run the following command. This step adds to the project a set of script files and assembly references that enable SignalR functionality.
install-package Microsoft.AspNet.SignalR
In Solution Explorer, expand the Scripts folder. Note that script libraries for SignalR have been added to the project.
In Solution Explorer, right-click the project, select Add | New Folder, and add a new folder named Hubs.
Right-click the Hubs folder, click Add | New Item, select the Visual C# | Web | SignalR node in the Installedpane, select SignalR Hub Class (v2) from the center pane, and create a new hub named ChatHub.cs. You will use this class as a SignalR server hub that sends messages to all clients.
Replace the code in the ChatHub class with the following code.
using System; using System.Web; using Microsoft.AspNet.SignalR; namespace SignalRChat { public class ChatHub : Hub { public void Send(string name, string message) { // Call the addNewMessageToPage method to update clients. Clients.All.addNewMessageToPage(name, message); } } }
Create a new class called Startup.cs. Change the contents of the file to the following.
using Owin; using Microsoft.Owin; [assembly: OwinStartup(typeof(SignalRChat.Startup))] namespace SignalRChat { public class Startup { public void Configuration(IAppBuilder app) { // Any connection or hub wire up and configuration should go here app.MapSignalR(); } } }
Edit the
HomeController
class found in Controllers/HomeController.cs and add the following method to the class. This method returns the Chat view that you will create in a later step.public ActionResult Chat() { return View(); }
Right-click the Views/Home folder, and select Add... | View.
In the Add View dialog, name the new view Chat.
Replace the contents of Chat.cshtml with the following code.
Important: When you add SignalR and other script libraries to your Visual Studio project, the Package Manager might install a version of the SignalR script file that is more recent than the version shown in this topic. Make sure that the script reference in your code matches the version of the script library installed in your project.
@{ ViewBag.Title = "Chat"; } <h2>Chat</h2> <div class="container"> <input type="text" id="message" /> <input type="button" id="sendmessage" value="Send" /> <input type="hidden" id="displayname" /> <ul id="discussion"> </ul> </div> @section scripts { <!--Script references. --> <!--The jQuery library is required and is referenced by default in _Layout.cshtml. --> <!--Reference the SignalR library. --> <script src="~/Scripts/jquery.signalR-2.1.0.min.js"></script> <!--Reference the autogenerated SignalR hub script. --> <script src="~/signalr/hubs"></script> <!--SignalR script to update the chat page and send messages.--> <script> $(function () { // Reference the auto-generated proxy for the hub. var chat = $.connection.chatHub; // Create a function that the hub can call back to display messages. chat.client.addNewMessageToPage = function (name, message) { // Add the message to the page. $('#discussion').append('<li><strong>' + htmlEncode(name) + '</strong>: ' + htmlEncode(message) + '</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(); }); }); }); // This optional function html-encodes messages for display in the page. function htmlEncode(value) { var encodedValue = $('<div />').text(value).html(); return encodedValue; } </script> }
Save All for the project.
Run the Sample
Press F5 to run the project in debug mode.
In the browser address line, append /home/chat to the URL of the default page for the project. The Chat page loads in a browser instance and prompts for a user name.
Enter a user name.
- 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.
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 a browser.
In Solution Explorer, inspect the Script Documents node for the running application. This node is visible in debug mode if you are using Internet Explorer as your browser. 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. If you use a browser other than Internet Explorer, you can also access the dynamichubs file by browsing to it directly, for example http://mywebsite/signalr/hubs.
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 theHub 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 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.addNewMessageToPage.
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 property to access all clients connected to this hub.
Call a function on the client (such as the
addNewMessageToPage
function) to update clients.public class ChatHub : Hub { public void Send(string name, string message) { Clients.All.addNewMessageToPage(name, message); } }
SignalR and jQuery
The Chat.cshtml view file 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 creating a reference to the auto-generated proxy for 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 reference to a hub proxy.
var chat = $.connection.chatHub;
Note: In JavaScript the reference to the server class and its members is in camel case. The code sample references the C# ChatHub class in JavaScript as chatHub. If you want to reference the
ChatHub
class in jQuery with conventional Pascal casing as you would in C#, edit the ChatHub.cs class file. Add ausing
statement to reference theMicrosoft.AspNet.SignalR.Hubs
namespace. Then add theHubName
attribute to theChatHub
class, for example[HubName("ChatHub")]
. Finally, update your jQuery reference to theChatHub
class.
The following code shows how to create a callback function in the script. The hub class on the server calls this function to push content updates to each client. The optional call to the htmlEncode
function shows a way to HTML encode the message content before displaying it in the page, as a way to prevent script injection.
chat.client.addNewMessageToPage = function (name, message) { // Add the message to the page. $('#discussion').append('<li><strong>' + htmlEncode(name) + '</strong>: ' + htmlEncode(message) + '</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 Chat page.
Note: This approach ensures 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 a simple SignalR application, see Using SignalR with Windows Azure Web Sites. 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.
To learn more advanced SignalR developments concepts, visit the following sites for SignalR source code and resources :
This article was originally created on June 10, 2014
SingalR--demo的更多相关文章
- ASP.NET SingalR + MongoDB 实现简单聊天室(三):实现用户群聊,总结完善
前两篇已经介绍的差不多了,本篇就作为收尾. 使用hub方法初始化聊天室的基本步骤和注意事项 首先确保页面已经引用了jquery和singalR.js还有对应的hubs文件,注意,MVC框架有时会将jq ...
- ASP.NET SingalR + MongoDB 实现简单聊天室(二):实现用户信息、聊天室初始化,聊天信息展示完善
第一篇已经介绍了一大半了,下面就是详细业务了,其实业务部分要注意的地方有几个,剩下的就是js跟html互动处理. 首先在强调一下,页面上不可缺少的js:jquery,singalR.js,hubs . ...
- 通过一个demo了解Redux
TodoList小demo 效果展示 项目地址 (单向)数据流 数据流是我们的行为与响应的抽象:使用数据流能帮我们明确了行为对应的响应,这和react的状态可预测的思想是不谋而合的. 常见的数据流框架 ...
- 很多人很想知道怎么扫一扫二维码就能打开网站,就能添加联系人,就能链接wifi,今天说下这些格式,明天做个demo
有些功能部分手机不能使用,网站,通讯录,wifi基本上每个手机都可以使用. 在看之前你可以扫一扫下面几个二维码先看看效果: 1.二维码生成 网址 (URL) 包含网址的 二维码生成 是大家平时最常接触 ...
- 在线浏览PDF之PDF.JS (附demo)
平台之大势何人能挡? 带着你的Net飞奔吧!:http://www.cnblogs.com/dunitian/p/4822808.html#skill 下载地址:http://mozilla.gith ...
- 【微框架】Maven +SpringBoot 集成 阿里大鱼 短信接口详解与Demo
Maven+springboot+阿里大于短信验证服务 纠结点:Maven库没有sdk,需要解决 Maven打包找不到相关类,需要解决 ps:最近好久没有写点东西了,项目太紧,今天来一篇 一.本文简介 ...
- vue双向数据绑定原理探究(附demo)
昨天被导师叫去研究了一下vue的双向数据绑定原理...本来以为原理的东西都非常高深,没想到vue的双向绑定真的很好理解啊...自己动手写了一个. 传送门 双向绑定的思想 双向数据绑定的思想就是数据层与 ...
- Android Studio-—使用OpenCV的配置方法和demo以及开发过程中遇到的问题解决
前提: 1.安装Android Studio(过程略) 2.官网下载OpenCV for Android 网址:http:opencv.org/downloads.html 我下载的是下图的版本 3. ...
- iOS之ProtocolBuffer搭建和示例demo
这次搭建iOS的ProtocolBuffer编译器和把*.proto源文件编译成*.pbobjc.h 和 *.pbobjc.m文件时,碰到不少问题! 搭建pb编译器到时没有什么问题,只是在把*.pro ...
- 钉钉开放平台demo调试异常问题解决:hostname in certificate didn't match
今天研究钉钉的开放平台,结果一个demo整了半天,这帮助系统写的也很难懂.遇到两个问题: 1.首先是执行demo时报unable to find valid certification path to ...
随机推荐
- html嵌套MP4、PDF的简单方案
你需要一个jquery.media插件,http://malsup.com/jquery/media/ 然后: <html><head><script src=" ...
- 让C#轻松实现读写锁分离--封装ReaderWriterLockSlim
ReaderWriterLockSlim 类 表示用于管理资源访问的锁定状态,可实现多线程读取或进行独占式写入访问. 使用 ReaderWriterLockSlim 来保护由多个线程读取但每次只采用一 ...
- 实战使用Axure设计App,使用WebStorm开发(6) – 迈向后端
系列文章 实战使用Axure设计App,使用WebStorm开发(1) – 用Axure描述需求 实战使用Axure设计App,使用WebStorm开发(2) – 创建 Ionic 项目 实战使 ...
- IOS Block-Block块的使用与理解
在IOS中,block块是新添加的语法,其他程序语言中也被称为闭包. 程序块的理念是像任何其他C语言类型一样对待特定的代码块.程序块可以分配给一个变量,以参数的形式传递给函数或方法,当然也可以执行(不 ...
- CSS折行小记
最近项目中遇到字段内容过长的显示问题. 后来在网上找了资料,http://www.php100.com/html/webkaifa/DIV_CSS/2009/0416/2453.html 用了td( ...
- ASP.NET将原始图片按照指定尺寸等比例缩放显示图片
网站上可能会有很多图片,比如产品图片等,而且他们可能大小不一,宽度和高度也不一定一样,有的很大有的很小.如果放在一张网页上,可能会破坏版面,但是如果强制让他们按照指定的宽度和高度显示,因为比例不同还会 ...
- Java线程:线程状态的转换
Java线程:线程状态的转换 一.线程状态 线程的状态转换是线程控制的基础.线程状态总的可分为五大状态:分别是生.死.可运行.运行.等待/阻塞.用一个图来描述如下: 1.新状态:线程对象已 ...
- 2013 duilib入门简明教程 -- 总结 (20)
duilib的入门系列就到尾声了,再次提醒下,Alberl用的duilib版本是SVN上第个版本,时间是2013.08.15~ 这里给出Alberl最后汇总的一个工程,戳我下载,效 ...
- Atiti 重定向标准输出到字符串转接口adapter stream流体系 以及 重定向到字符串
Atiti 重定向标准输出到字符串转接口adapter stream流体系 以及 重定向到字符串 原理::syso 向ByteArrayOutputStream这个流理想write字节..然后可以使 ...
- salesforce 零基础学习(二十七)VF页面等待(loading)效果制作
进行查询的情况下,显示友好的等待效果可以让用户更好的了解目前的状态以及减少用户消极的等待,例如下图所示. VF提供了<apex:actionStatus>标签,,此标签用于显示一个AJAX ...