所需环境:SignalR运行在.NET 4.5平台上,这里演示时采用ASP.NET MVC 3;
一.简介
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<myconnection>("echo","echo/{*operation}");
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
在前台页面中添加如下html代码:
<script type="text/javascript">
$(function () {
var connection = $.connection('echo');
connection.received(function (data) {
$('#messages').append('<li>' + data + '</li>');
});
connection.start();
$("#broadcast").click(function () {
connection.send($('#msg').val());
});
$("#btnStop").click(function () {
connection.stop();
});
});
</script>
<h3>@ViewBag.Message</h3>
<input type="text" id="msg" />
<input type="button" id="broadcast" value="发送" />
<input type="button" id="btnStop" value="停止" />
<ul id="messages">
</ul>
可在
方法中进行消息的监视。
b).实现Hubs
新建Chat.cs类,代码如下:
namespace MvcApplicationSignalR
{
[HubName("chat")]
public class Chat : Hub
{
public void Send(string clientName, string message)
{
Clients.addSomeMessage(clientName, message);
}
}
}
前台模板html代码如下:
<head>
<meta charset="utf-8" />
<title>@ViewBag.Title</title>
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery-1.6.4.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery-ui-1.8.24.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.signalR-0.5.3.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/signalr/hubs")" type="text/javascript"></script>
</head>
后台代码如下:
public ActionResult HubChat()
{
ViewBag.ClientName = "用户-" + Rnd.Next(1, 9);
return View();
}
对应的视图代码为:
@model dynamic
@{
ViewBag.Title = "title";
}
<script src="@Url.Content("~/Scripts/hubDemo.js")" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
});
</script>
<h3>Hub Chat</h3>
<div>
<input type="text" id="Placeholder" value="@ViewBag.ClientName" hidden="true"/>
<input type="text" id="msg" />
<input type="button" id="broadcast" value="广播" />
<br />
<br />
<h4>
消息记录: (你是:<span id="MyClientName">@ViewBag.ClientName</span>):
</h4>
<ul id="messages">
</ul>
</div>
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('<b>' + clientName + '</b> 对大家说: ' + 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('<li class="' + logClass + '"><b>' + nowStr + '</b> ' + eventLog + '.</li>');
}
});
资源:
一个很酷的同步操作表格的示例(使用 jTable ):
http://www.codeproject.com/Articles/315938/Real-time-Asynchronous-Web-Pages-using-jTable-Sign
组通知示例:
http://www.codeproject.com/Articles/404662/SignalR-Group-Notifications
先写到这里,以后在深度研究
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。