引用
Microsoft.AspNet.SignalR
服务器
自定义Connection
public class BarrageConnection : PersistentConnection
{
protected override Task OnReceived(IRequest request, string connectionId, string data)
{
//在这里可以做自己的业务处理,比如把弹幕存进redis等等
return Connection.Broadcast(data, connectionId);
}
}
Map SignalR
[assembly: OwinStartup(typeof(BarrageDemo2.Website.Startup))]
namespace BarrageDemo2.Website
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR<BarrageConnection>("/barrageConnection");
}
}
}
客户端
引用
<!--引用Microsoft.AspNet.SignalR后自动添加-->
<script src="~/Scripts/jquery.signalR-2.2.2.min.js"></script>
创建连接
connection = $.connection("/barrageConnection");
发送消息
connection.send({ userName: userName, comment: comment });
接收消息
connection.received(function (data) {
var bulletObj = JSON.parse(data);
//......
});
示例代码
https://github.com/zLulus/BarrageDemo/tree/master/BarrageDemo2.Website
参考资料
Microsoft.AspNet.SignalR介绍,用于任何即时性的功能
https://docs.microsoft.com/en-us/aspnet/signalr/overview/getting-started/introduction-to-signalr?WT.mc_id=DT-MVP-5003010