所需环境:SignalR运行在.NET 4.5平台上,这里演示时采用ASP.NET MVC 3;
临猗网站建设公司创新互联,临猗网站设计制作,有大型网站制作公司丰富经验。已为临猗1000多家提供企业网站建设服务。企业网站搭建\成都外贸网站建设公司要多少钱,请找那个售后服务好的临猗做网站的公司定做!
一.简介
ASP .NET SignalR 是一个ASP .NET 下的类库,可以在ASP .NET 的Web项目中实现实时通信。
二.原理
其实现原理跟WCF或Remoting相似,均为使用远程代理来实现。实现接口有2种分别是PersistentConnection 和 Hubs,其中PersistentConnection 是实现长时间js轮循的,Hub是用来解决实时信息交换问题,其利用js动态载入方法实现,客户端与服务器端全部使用json来交换数据。
三.Demo创建
1.打开NuGet 安装 Microsoft ASP.NET SignalR

2.实现
a).实现PersistentConnection
添加myconnection.cs文件
namespace MvcApplicationSignalR
{
public class myconnection : PersistentConnection
{
protected override Task OnReceivedAsync(string clientId, string data)
{
// Broadcast data to all clients
data = string.Format("数据是:{0} 时间是:{1}", data, DateTime.Now.ToString());
//return Connection.Broadcast(data);
return Send(clientId, data);
}
}
}在Global.asax.cs文件中注册一下代码(第3行):
protected void Application_Start()
{
RouteTable.Routes.MapConnection("echo","echo/{*operation}");
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
} 在前台页面中添加如下html代码:
@ViewBag.Message
执行效果如下:

可在
protectedoverrideTask OnReceivedAsync(stringclientId, stringdata)
方法中进行消息的监视。
b).实现Hubs
新建Chat.cs类,代码如下:
namespace MvcApplicationSignalR
{
[HubName("chat")]
public class Chat : Hub
{
public void Send(string clientName, string message)
{
Clients.addSomeMessage(clientName, message);
}
}
}前台模板html代码如下:
@ViewBag.Title
后台代码如下:
public ActionResult HubChat()
{
ViewBag.ClientName = "用户-" + Rnd.Next(1, 9);
return View();
}对应的视图代码为:
@model dynamic
@{
ViewBag.Title = "title";
}
Hub Chat
消息记录: (你是:@ViewBag.ClientName):
hubDemo.js所对应的内容如下:
$(function () {
var myClientName = $('#Placeholder').val();
// Proxy created on the fly
var chat = $.connection.chat;
// Declare a function on the chat hub so the server can invoke it
chat.addSomeMessage = function (clientName, message) {
writeEvent('' + clientName + ' 对大家说: ' + message, 'event-message');
};
$("#broadcast").click(function () {
// Call the chat method on the server
chat.send(myClientName, $('#msg').val())
.done(function () {
console.log('Sent message success!');
})
.fail(function (e) {
console.warn(e);
});
});
// Start the connection
$.connection.hub.start();
//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('资源:
一个很酷的同步操作表格的示例(使用 jTable ):
http://www.codeproject.com/Articles/315938/Real-time-Asynchronous-Web-Pages-using-jTable-Sign
组通知示例:
http://www.codeproject.com/Articles/404662/SignalR-Group-Notifications
先写到这里,以后在深度研究
Copyright © 2009-2022 www.wtcwzsj.com 青羊区广皓图文设计工作室(个体工商户) 版权所有 蜀ICP备19037934号