前言:SignalR是一种针对H5中WebSocket的解决方案,可以实现在不支持H5的浏览器中实现IM
后端:
step 1:通过NuGet安装SignalR
step 2:新建一个类继承于Hub,code belows:
[HubName("jzHub")]
public class MyHub:Hub
{ public void SendMsg(string name,string msg)
{ //Clients.All.sayHi(name,msg);
Clients.Others.sayHi(name, msg);
}
}
step 3:新建一个类Startup,code belows:
[assembly :OwinStartup(typeof(TestSignalR.Startup))]
namespace TestSignalR
{
public class Startup
{
public void Configuration(IAppBuilder app) {
app.MapSignalR();
}
}
}
UI界面:
step 4:新建一个Html页面:
<body>
<form id="form1" runat="server">
<div>
<ul id="msg_list"> </ul>
<input type="text" id="txtName" />
<input type="text" id="txtMsg" />
<input type="button" id="btnSend" value="发送" /> </div>
</form>
<script src="Scripts/jquery-2.2.3.min.js"></script>
<script src="Scripts/jquery.signalR-2.2.0.min.js"></script>
<script src="/signalR/hubs"></script>
<script type="text/javascript"> $(function () {
"use strict";
var hubProxy=$.connection["jzHub"];
hubProxy.client.sayHi = function (name, msg) { $("#msg_list").append("<li><strong>" + name + "</strong>:" +msg + "</li>"); } $.connection.hub.start().done(function () {
$("#btnSend").on("click", function () { hubProxy.server.sendMsg($("#txtName").val(), $("#txtMsg").val()); }) }) }) </script>
</body>
运行即可实现即时通讯。。。