一、新建项目,选MVC项目默认 添加mvc文件夹和核心引用
二、添加SignaIR包
SignalR的准备:NuGet包管理器搜索:工具——>库程序包管理器——>Microsoft.AspNet.SignalR 或者 工具——>库程序包管理器——>程序包管理器控制台 Install-Package Microsoft.AspNet.SignalR。
三、新建startup文件(在App_Start目录内),用来启动SignalR
选择常规-->选择OWIN Startup类-->修改名字: StartupSignalR.cs
StartupSignalR.cs内添加 永久链接类的配置;//启动SignalR --详情进入文件类查看
StartupSignalR.cs
using System; using System.Threading.Tasks; using demo1.HubSignalR; //一、这个是集线器引用命名空间 using Microsoft.Owin; using Owin; [assembly: OwinStartup(typeof(demo1.App_Start.StartupSignalR))] namespace demo1.App_Start { public class StartupSignalR { public void Configuration(IAppBuilder app) { // 有关如何配置应用程序的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkID=316888 //二、(SignalR永久连接类(v2)的配置,在前端调用)对应 public class HubConnection : PersistentConnection 中继承的HubConnection类 app.MapSignalR<HubConnection>("/HubSignalR/HubConnection"); } } }
demo1.HubSignalR
using Microsoft.AspNet.SignalR; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Web; namespace demo1.HubSignalR { public class HubConnection : PersistentConnection { protected override Task OnConnected(IRequest request, string connectionId) { return Connection.Send(connectionId, "Welcome!"); } protected override Task OnReceived(IRequest request, string connectionId, string data) { return Connection.Broadcast(data); } } }
四、客户端代码(新建Index控制器并添加视图,视图代码如下:)
@{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>PersistentConnection</title> <!--引用JQ库. --> <script src="~/scripts/jquery-1.6.4.min.js"></script> <!--引用SignalR库. --> <script src="~/scripts/jquery.signalR-2.3.0.min.js"></script> <script type="text/javascript"> $(function () { // 声明PersistentConnection连接 var connection = $.connection("/HubSignalR/HubConnection"); $('#displayname').val(prompt('Enter your name:', '')); $("msg").focus(); // 接收内容 connection.received(function (data) { $('#messages').append('<li>' + data + '</li>'); }); // 开启连接 connection.start().done(function () { $("#broadcast").click(function () { // 发送内容 connection.send($('#displayname').val() + ':' + $('#msg').val()); }); }); }); </script> </head> <body> <input type="text" id="msg" /> <input type="button" id="broadcast" value="broadcast" /> <input type="hidden" id="displayname" /> <ul id="messages"></ul> </body> </html>