1,SignalR是一个运行在.NET 平台上的 html websocket 框架,它出现的主要目的是实现服务器主动推送(Push)消息到客户端页面 具体使用如下:
一、安装
打开管理NuGet程序包,搜索SignalR,安装下面这些程序包
安装完成后程序中会多出一些引用
二、使用
因为用的是SignalR2,所以需要新建Startup.cs类,配置集线器,编写如下
using Microsoft.Owin; using Owin; [assembly: OwinStartupAttribute(typeof(MvcSignalR.Startup))] namespace MvcSignalR { public partial class Startup { public void Configuration(IAppBuilder app) { app.MapSignalR(); } } }
接着编写HUb类
using Microsoft.AspNet.SignalR; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Web; namespace MvcSignalR.Services { /// <summary> /// 数据交流类 /// </summary> public class ChatServiceHub : Hub { //所有的ConnectionId,时间的作用将来设置定时器,每隔多长时间清理下无用的ConnectionId public static ConcurrentDictionary<string, DateTime> AllConnectionIDs = new ConcurrentDictionary<string, DateTime>(); //用户的ConnectionID,一个ID对应一个用户 public static ConcurrentDictionary<string, string> UserConnectionIDs = new ConcurrentDictionary<string, string>(); private Random rd = new Random(); public void Send(string message) { int i = 0; while (i < 10000) { i++; Thread.Sleep(100); Clients.Client(Context.ConnectionId).broadcastMessage(Context.ConnectionId, message + rd.Next(1000)); } } public void SendMessage(string message) { Clients.Client(Context.ConnectionId).receiveMessage(message + rd.Next(1000)); } public override Task OnConnected() { AllConnectionIDs.AddOrUpdate(Context.ConnectionId, DateTime.Now, (key, oldValue) => DateTime.Now); return base.OnReconnected(); } } }
编写前端代码
引用js
$(function () { // Declare a proxy to reference the hub. var chat = $.connection.chatServiceHub; // 接受信息 chat.client.receiveMessage = function (message) { receiveMessage(message); }; var hubStartDone = function () { $.connection.hub.start().done(); }; hubStartDone(); $.connection.hub.disconnected(function () { setTimeout(function () { console.log("disconnected"); hubStartDone(); }, 50000); // Restart connection after 50 seconds. });
//发送信息 $('.sendBtn').on('click', function () { debugger var news = $('#dope').val(); if (news == '') { alert('不能为空'); } else { chat.server.sendMessage(news); } });
function receiveMessage(message) { var answer = ''; answer += '<li>' + '<div class="answerHead"><img src="/Images/qq/1003.jpg"/></div>' + '<div class="answers"><img class="jiao" src="/Images/qq/jiao.jpg">' + message + '</div>' + '</li>'; $('.newsList').append(answer); $('.RightCont').scrollTop($('.RightCont')[0].scrollHeight); } });