(一)、.NET必须4.5。没有下载好pack包的,需要在NuGet包管理器里的控制台里执行以下两句代码安装必要Dll:
1.Install-Package Microsoft.AspNet.SignalR
2.Install-Package Microsoft.Owin.Cors
1.Install-Package Microsoft.AspNet.SignalR
2.Install-Package Microsoft.Owin.Cors
如果有现成的Dll,需要引用下图中红框Dll
(二)、创建Hub类
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using System.Threading.Tasks;
namespace SignalR.Hubs {
[HubName("chatHub")]
public class ChatHub:Hub {
public override Task OnConnected() {
Clients.Caller.sayHello("连接成功");
return base.OnConnected();
}
public override Task OnReconnected() {
return base.OnReconnected();
}
public override Task OnDisconnected(bool stopCalled) {
return base.OnDisconnected(stopCalled);
}
[HubMethodName("hello")]
public void Hello(string name) {
Clients.All.sayHello2("第二次");
Clients.All.sayHello3(Context.ConnectionId);
}
}
}
(二)、创建Startup类
using Microsoft.Owin.Cors;
using Owin;
namespace SignalR {
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
app.Map("/signalr", map => {
map.UseCors(CorsOptions.AllowAll);
map.RunSignalR();
});
}
}
}
(三)、创建空的HTML页面
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h2>服务端</h2>
</body>
</html>
客户端:
(四)、注意点就是需要引用动态生成JS:signalr/hubs
引用jqeury、signalR.js、signalr/hubs
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>客户端</title>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.signalR-2.2.1.min.js"></script>
<!--http://localhost:6717/signalr/hubs IP地址为服务器端,必须引用-->
<script src="http://localhost:6717/signalr/hubs"></script>
</head>
<body>
<script>
//chatHub是服务端创建的Hub类
var chat = $.connection.chatHub;
//signalr是服务端Startup类里路由名称
chat.connection.url = "http://localhost:6717/signalr";
//成功连接后,调用服务器Hello方法,手写字母必须小写
$.connection.hub.start().done(function () {
chat.server.hello("hello");
});
//服务器Hello方法返回的方法
chat.client.sayHello2 = function (msg) {
alert(msg);
};
//服务器Hello方法返回的方法
chat.client.sayHello3 = function (msg) {
alert(msg);
};
</script>
</body>
</html>