一,Persistent Connection 演示示例教程

1。实现server端代码

1),编写server PersistentConnection 代码

项目中 SignalR 文件夹下创建 PersistentConnection.cs 文件

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using SignalR; namespace SignalTutorial.SignalR
{
public class MyConnection : PersistentConnection
{
protected override Task OnConnectedAsync(IRequest request, string connectionId)
{
return Connection.Broadcast("Connection " + connectionId + " connected");
} protected override Task OnReconnectedAsync(IRequest request, IEnumerable<string> groups, string clientId)
{
return Connection.Broadcast("Client " + clientId + " re-connected");
} protected override Task OnReceivedAsync(IRequest request, string connectionId, string data)
{
var info = data + ". ConnectionId is [" + connectionId + "]";
// return Connection.Send(connectionId, info); // Broadcast data to all clients
return Connection.Broadcast(info);
} protected override Task OnDisconnectAsync(string connectionId)
{
return Connection.Broadcast("Connection " + connectionId + " disconncted");
} protected override Task OnErrorAsync(Exception error)
{
return Connection.Broadcast("Error ocurred " + error);
}
}
}

1,MyConnection 继承自 PersistentConnection,这样我们就能在client连接,重连接,断开连接,发送消息以及连接出错的情况下进行相关的处理。从以下的 PersistentConnection 接口中能够看到,PersistentConnection 相同支持组进行推送。

2。推送消息由 PersistentConnection 的属性 Connection 来提供。它继承自 IConnection 接口。该接口提供两个函数来实现对特定client的推送和广播功能。

System.Threading.Tasks.Task Send(string signal, object value)

System.Threading.Tasks.Task Broadcast(object value)

2)。配置訪问路由

为了支持client訪问,我们将对路由表中进行配置。打开 Global.asax.cs 。改动 Application_Start() 函数例如以下:

protected void Application_Start()
{
AreaRegistration.RegisterAllAreas(); RouteTable.Routes.MapConnection<MyConnection>("echo", "echo/{*operation}"); RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes); // Make connections wait 50s maximum for any response. After
// 50s are up, trigger a timeout command and make the client reconnect.
GlobalHost.Configuration.ConnectionTimeout = TimeSpan.FromSeconds(50);
//DisconnectTimeout
//HeartBeatInterval
//KeepAlive
}

在上面的代码中。我将 echo 及其子路径的訪问映射到 MyConnection 上。并设置连接超时时间为 50 s。在这里还能够设置其它的一些參数,如断连超时时间,心跳间隔等。

2。实现client代码

@model dynamic

@{
ViewBag.Title = "title";
} <script src="@Url.Content("~/Scripts/persistent.js")" type="text/javascript"></script> <h2>Persistent Chat</h2> <div>
<input type="text" id="Placeholder" value="@ViewBag.ClientName" hidden="true"/>
<input type="text" id="msg" />
<input type="button" id="broadcast" value="广播" /> <br />
<br /> <h3>
消息记录: (你是:<span id="MyClientName">@ViewBag.ClientName</span>):
</h3> <ul id="messages">
</ul> </div>
2),编写 Javascript

向 Scripts 文件夹加入新的 Javescript 脚本:persistent.js。其内容例如以下:

$(function () {

    var myClientName = $('#Placeholder').val();

    var connection = $.connection('/echo');

    connection.received(function (data) {
var msg = new String(data);
var index = msg.indexOf("#");
var clientName = msg.substring(0, index);
var content = msg.substring(index + 1); if (clientName == null || clientName == "") {
writeEvent('<b>' + "系统消息" + '</b>: ' + content, 'event-message');
}
else {
writeEvent('<b>' + clientName + '</b> 对大家说: ' + content, 'event-message');
}
}); connection.start(); $("#broadcast").click(function () {
var msg = myClientName + "#" + $('#msg').val();
connection.send(msg);
}); //A function to write events to the page
function writeEvent(eventLog, logClass) {
var now = new Date();
var nowStr = now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds();
$('#messages').prepend('<li class="' + logClass + '"><b>' + nowStr + '</b> ' + eventLog + '.</li>');
}
});

1。创建连接时。指定路径为 "/echo"。该路径在server端的路由映射表被映射为 MyConnection。因而这个连接就被指向前面提供 MyConnection。

2,将 clientName 信息成 message 在,同 # 将 clientName 和消息内容被连接到一个 msg。

Asp.NET MVC3 使用 SignalR 实现推(持续)的更多相关文章

  1. Asp.NET MVC3 使用 SignalR 实现推

    一,简单介绍 Signal 是微软支持的一个执行在 Dot NET 平台上的 html websocket 框架. 它出现的主要目的是实现server主动推送(Push)消息到client页面,这样c ...

  2. Asp.NET MVC 使用 SignalR 实现推送功能二(Hubs 在线聊天室 获取保存用户信息)

    简单介绍 关于SignalR的简单实用 请参考 Asp.NET MVC 使用 SignalR 实现推送功能一(Hubs 在线聊天室) 在上一篇中,我们只是介绍了简单的消息推送,今天我们来修改一下,实现 ...

  3. Asp.NET MVC 使用 SignalR 实现推送功能一(Hubs 在线聊天室)

    简介       ASP .NET SignalR 是一个ASP .NET 下的类库,可以在ASP .NET 的Web项目中实现实时通信.什么是实时通信的Web呢?就是让客户端(Web页面)和服务器端 ...

  4. Asp.NET websocket,Asp.NET MVC 使用 SignalR 实现推送功能一(Hubs 在线聊天室)

    ASP .NET SignalR 是一个ASP .NET 下的类库,可以在ASP .NET 的Web项目中实现实时通信.什么是实时通信的Web呢?就是让客户端(Web页面)和服务器端可以互相通知消息及 ...

  5. WinForm中 Asp.Net Signalr消息推送测试实例

    p{ text-align:center; } blockquote > p > span{ text-align:center; font-size: 18px; color: #ff0 ...

  6. 在 Asp.NET MVC 中使用 SignalR 实现推送功能 [转]

    在 Asp.NET MVC 中使用 SignalR 实现推送功能 罗朝辉 ( http://blog.csdn.net/kesalin ) CC许可,转载请注明出处 一,简介 Signal 是微软支持 ...

  7. 【转】asp.net mvc3 简单缓存实现sql依赖

    asp.net mvc3 简单缓存实现sql依赖   议题 随 着网站的发展,大量用户访问流行内容和动态内容,这两个方面的因素会增加平均的载入时间,给Web服务器和数据库服务器造成大量的请求压力.而大 ...

  8. MVC 中使用 SignalR 实现推送功能

    MVC 中使用 SignalR 实现推送功能 一,简介 Signal 是微软支持的一个运行在 Dot NET 平台上的 html websocket 框架.它出现的主要目的是实现服务器主动推送(Pus ...

  9. ASP.NET Core & Docker & Jenkins 零基础持续集成实战

    原文:ASP.NET Core & Docker & Jenkins 零基础持续集成实战 一.本系列教程说明 源代码管理工具:Gogs 持续集成工具:Jenkins 容器:Docker ...

随机推荐

  1. Mars之android的Handler(2)

    handler .looper.messageque的关系在前面已经有个介绍,但前面handler(1)中handler的使用是极少的一种情况,因为handler.sendMessage()可以在Ma ...

  2. Android中G-Sensor相关流程

    1.使G-sensor正常工作需要做的事: G-sensor driver文件包括: driver/i2c/chips/lis331dl.c driver/i2c/chips/sensorioctl. ...

  3. .net设计模式 - 单例模式

    DoNet设计模式实例之单例模式( Singleton Pattern) 一 : 单例模式的简介:(Brief Introduction) 单例模式(Singleton Pattern),保证一个类只 ...

  4. Linux mysql 数据库忘记root密码

    1.修改MySQL的登录设置: # vi /etc/my.cnf 1在[mysqld]的段中加上一句:skip-grant-tables 保存并且退出vi. 2.重新启动mysqld # /etc/i ...

  5. 新西兰gap year_百度百科

    新西兰gap year_百度百科 新西兰gap year    Working Holiday Visa,即打工度假签证.它允许旅行者出于补贴旅行费用的目的而在签证颁发国边打工边旅行.用来鼓励双方国家 ...

  6. Lucene全文检索的【增、删、改、查】 实例

    创建索引 Lucene在进行创建索引时,根据前面一篇博客,已经讲完了大体的流程,这里再简单说下: Directory directory = FSDirectory.open("/tmp/t ...

  7. JAVA 保留两位小数的四种方法

    import java.math.BigDecimal; import java.text.DecimalFormat; import java.text.NumberFormat; publiccl ...

  8. Callable 获取线程返回值

    allable与 Future 两功能是Java在兴许版本号中为了适应多并法才增加的,Callable是类似于Runnable的接口,实现Callable接口的类和实现Runnable的类都是可被其它 ...

  9. 时间复杂度为O(nlogn)的LIS算法

    时间复杂度为 n*logn的LIS算法是用一个stack维护一个最长递增子序列 如果存在 x < y 且  a[x] > a[y],那么我们可以用a[y]去替换a[x] 因为a[y]比较小 ...

  10. 轻量级分布式RPC框架

    随笔- 139  文章- 0  评论- 387  一个轻量级分布式RPC框架--NettyRpc   1.背景 最近在搜索Netty和Zookeeper方面的文章时,看到了这篇文章<轻量级分布式 ...