项目中 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); } } }
2,推送消息由 PersistentConnection 的属性 Connection 来提供,它继承自 IConnection 接口,该接口提供两个函数来实现对特定客户端的推送和广播功能。
System.Threading.Tasks.Task Send(string signal, object value)
System.Threading.Tasks.Task Broadcast(object value)
为了支持客户端访问,我们将对路由表中进行配置。打开 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 }
@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>
向 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",该路径在服务器端的路由映射表被映射为 MyConnection,因而这个连接就被指向前面提供的 MyConnection。
2,将 clientName 信息放入 message 中,并用 # 将 clientName 和消息内容连接成一个 msg。
Asp.NET MVC3 使用 SignalR 实现推送(接上),布布扣,bubuko.com
Asp.NET MVC3 使用 SignalR 实现推送(接上)
原文地址:http://blog.csdn.net/yancongmin0702/article/details/24931075