What is SignalR

ASP.NET SignalR is a new library for ASP.NET developers that simplifies the process of adding real-time web functionality to your applications. Real-time web functionality is the ability to have server-side code push content to connected clients instantly as it becomes available.

You may have heard of the HTML5 WebSocket API that enables efficient bidirectional communication between the browser and server. SignalR uses Websockets when it is supported by the browser and the server, and gracefully falls back to other techniques and technologies when it is not. Either way, your application code stays the same.

SignalR provides a simple ASP.NET API for creating server-to-client remote procedure calls (RPC) that call JavaScript functions in client browsers from server-side .NET code. SignalR also includes API for connection management (for instance, connect and disconnect events), grouping connections, and authorization.

上面是http://www.asp.net/signalr 的介绍。

本人英文不太好,简单翻译一下就是:SignalR是一个新的类库,它为ASP.NET开发者提供一个更简单的途径实现实时在线功能。SignalR可以实现服务端推送内容到客户端的功能。SignalR通过HTML5的WebSocket来实现服务端跟浏览器的通信。如果浏览器不支持WebSocket 那么就用其他的技术来实现。不管哪种技术,最后都是同样的效果。SignalR提供一组简单的ASP.NET API去构建RPC功能。它可以通过服务端代码去调用前端的javascript方法。SignalR同样为连接管理,群组连接,权限等提供了API。

/*以下不是翻译*/

SignalR非常微软,它被微软封装的非常易用。不管是后台类库,还是前端javascript都已经被你封装好了。SignalR依赖JQuery。SignalR的实现原理类似WCF,使用javascript代理类来调用服务端的方法。废话不多了上代码吧。

后台:

新建一个空的MVC项目,添加一个最基本的View跟Controller这个就不废话了。

在Global.asax的Start方法下面添加:

  RouteTable.Routes.MapHubs();

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

初始化hub。

在在解决方案下新建文件夹:Hub。添加一个类叫ChatHub:

  public class ChatHub : Microsoft.AspNet.SignalR.Hub
{
public void Send(string name, string message)
{
//send message to all pages
Clients.All.SentMsgToPages(name, message);
}
}
啊,太简单了。只有一个方法一行代码。这个Send方法是提供给Client调用的。其中SentMsgToPages这是个动态方法,它表示前端的回调方法。也就是说Client调用Send方法把name跟message传回server,然后server会回调所有的连接的client的SentMsgToPages方法,把name跟message提供到client。

前台:

@{
ViewBag.Title = "Index";
}
<script src="~/Scripts/jquery.signalR-1.1.2.js"></script>
<script src="~/signalr/hubs"></script> <script type="text/javascript">
var chat = $.connection.chatHub;
chat.client.SentMsgToPages = function (name, message) {
// Add the message to the page.
$('#msgUl').append('<li><strong>' + name
+ '</strong>: ' + message + '</li>');
};
function sendMsg() {
var userName = $("#userName").val();
if (!userName) {
$(".alert").show();
return;
}
var msg = $('#messageBox').val();
if (msg) {
chat.server.send(userName, msg);
$('#messageBox').val('').focus();
} }
$.connection.hub.start().done(
function() {
//设置按钮事件
$("#btnSent").click(
sendMsg
);
$("#userName").focus(
function () {
$(".alert").hide();
}
);
}
);
$(document).ready(
function () {
//设置高度
var msgListH = window.innerHeight - 150;
$(".messageList").height(msgListH);
$('#messageBox').keypress(
function(e) {
var key = e.keyCode;
if (key == 13) {
sendMsg();
}
}
);
}
);
</script>
<h2>SignalR Chat Room</h2>
<div style="width: 99%;margin: 4px" id="outBoard" >
<div class="messageList" >
<ul id="msgUl" class="unstyled"> </ul>
</div>
<div class="form-inline">
<input type="text" id="userName" placeholder="昵称" class="input-mini" />
<input type="text" id="messageBox" class="input-xxlarge"/>
<input type="submit" value="发送" class="btn btn-info" id="btnSent" /> </div>
<div class="alert" style="display: none; width: 100px">
必须输入昵称!
</div>
</div> 前台除去HTML其实也很简单。最关键的也就3句话。
1 var chat = $.connection.chatHub;
客户端跟服务端建立连接。
2 chat.client.SentMsgToPages = function (name, message) { };
这就是服务端回调客户端的方法,给SentMsgToPages实现一个function表示如何处理返回值,这里当然是把message添加到聊天记录列表里。
3 chat.server.send(userName, msg); 
客户端通过chat对象调用服务端的send方法,把数据传回到服务器。

效果:

我们如此简单的就实现了一个最基本的聊天室,SignalR当然还可以做网页通知的推送,实时的进度条等等。这对ASP.NET程序员来说真是又一个神器。

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

使用SignalR构建一个最基本的web聊天室的更多相关文章

  1. .net core下使用FastHttpApi构建web聊天室

    一般在dotnet core下构建使用web服务应用都使用asp.net core,但通过FastHttpApi组建也可以方便地构建web服务应用,在FastHttpApi功能的支持下构建多人聊天室是 ...

  2. Netty学习摘记 —— 简单WEB聊天室开发

    本文参考 本篇文章是对<Netty In Action>一书第十二章"WebSocket"的学习摘记,主要内容为开发一个基于广播的WEB聊天室 聊天室工作过程 请求的 ...

  3. 构建一个用于产品介绍的WEB应用

    为了让用户更好地了解您的产品功能,您在发布新产品或者升级产品功能的时候,不妨使用一个产品介绍的向导,引导用户熟悉产品功能和流程.本文将给您介绍一款优秀的用于产品介绍的WEB应用. 就像微博或邮箱这类W ...

  4. 如何构建一个多人(.io) Web 游戏,第 2 部分

    原文:How to Build a Multiplayer (.io) Web Game, Part 2 探索 .io 游戏背后的后端服务器. 上篇:如何构建一个多人(.io) Web 游戏,第 1 ...

  5. ASP.NET SignalR 与 LayIM2.0 配合轻松实现Web聊天室(十二) 代码重构使用反射工厂解耦(一)缓存切换

    前言 上一篇中,我们用了反射工厂来解除BLL和UI层耦合的问题.当然那是最简单的解决方法,再复杂一点的程序可能思路相同,但是在编程细节中需要考虑的就更多了,比如今天我在重构过程中遇到的问题.也是接下来 ...

  6. ASP.NET SignalR 与 LayIM2.0 配合轻松实现Web聊天室(零) 前言

    前端时间听一个技术朋友说 LayIM 2.0 发布了,听到这个消息抓紧去官网看了一下.(http://layim.layui.com/)哎呀呀,还要购买授权[大家支持一下哦],果断买了企业版,喜欢钻研 ...

  7. ASP.NET SignalR 与 LayIM2.0 配合轻松实现Web聊天室(一) 之 基层数据搭建,让数据活起来(数据获取)

    大家好,本篇是接上一篇 ASP.NET SignalR 与 LayIM2.0 配合轻松实现Web聊天室(零) 前言  ASP.NET SignalR WebIM系列第二篇.本篇会带领大家将 LayIM ...

  8. ASP.NET SignalR 与 LayIM2.0 配合轻松实现Web聊天室(二) 之 ChatServer搭建,连接服务器,以及注意事项。

    上篇:ASP.NET SignalR 与 LayIM2.0 配合轻松实现Web聊天室(一) 之 基层数据搭建,让数据活起来(数据获取) 上一篇我们已经完成了初步界面的搭建工作,本篇将介绍IM的核心内容 ...

  9. ASP.NET SignalR 与 LayIM2.0 配合轻松实现Web聊天室(三) 之 实现单聊,群聊,发送图片,文件。

    上篇讲解了如何搭建聊天服务器,以及客户端js怎么和layui的语法配合.服务器已经连接上了,那么聊天还会远吗? 进入正题,正如上一篇提到的我们用 Client.Group(groupId)的方法向客户 ...

随机推荐

  1. 常用jquery插件资料

    fullPage.js 全屏滚动https://github.com/alvarotrigo/fullPage.js Lava Lamp 导航条熔岩灯http://lavalamp.magicmedi ...

  2. 准备开源一套异形UI控件

    今天整理磁盘,发现在一个以前加密过的一个磁盘文件中发现了一些以前做的UI代码.平时都没怎么去用,放着放着只会慢慢的去遗忘,所以打算慢慢的将一些UI代码整理整理,然后开源出来,集合广大Delphier的 ...

  3. Android学习笔记----解决“com.android.dex.DexIndexOverflowException: method ID not in [0, 0xffff]: 65536”问题

    同时在工程中引入了多个第三方jar包,导致调用的方法数超过了android设定的65536个(DEX 64K problem),进而导致dex无法生成,也就无法生成APK文件. 解决办法如下: 1.谷 ...

  4. gitignore for vs

    */**/bin/Debug*/**/bin/Release*/**/obj/Debug*/**/obj/Release*/**/x86/Debug*/**/x86/Release*/**/x64/D ...

  5. config中自定义配置

    1. 定义自己的KeyValue <section name="TestKeyValue" type="System.Configuration.NameValue ...

  6. 学习之路三十九:新手学习 - Windows API

    来到了新公司,一开始就要做个程序去获取另外一个程序里的数据,哇,挑战性很大. 经过两周的学习,终于搞定,主要还是对Windows API有了更多的了解. 文中所有的消息常量,API,结构体都整理出来了 ...

  7. eclipse 编译出错(java.io.ObjectInputStream)的解决办法

    Multiple markers at this line - The type java.io.ObjectInputStream cannot be resolved. It is indirec ...

  8. 免费WebService服务

    国内手机号码归属地查询:http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx 中国股票及时行情数据:http://webservi ...

  9. ux.form.field.Verify 验证码控件

    //验证码控件 Ext.define('ux.form.field.Verify', { extend: 'Ext.container.Container', alias: ['widget.fiel ...

  10. ios 数组排序

    第一种:利用数组的sortedArrayUsingComparator调用 NSComparator  示例: obj1和obj2指的是数组中的对象 //1.数组中存放的是字符 NSComparato ...