工作上遇到一个推送消息的功能的实现。本着面向百度编程的思想。网上百度了一大堆。主要的实现方式是原生的WebSocket,和SignalR,再次写一个关于Asp.Net SignalR 的demo
这里简单的介绍一下Signalr,SignalR 封装了WebSocket、ForeverFrame、ServerSentEvents、LongPolling四种主要的传输协议。兼容性比较好,WebSocket 是有要求的,IIS服务需要系统是Win8或者 Server 2012 以上。下面开始撸代码。
1.首先建立一个项目。
2.通过包管理工具,引入SignalR
3.引入之后,需要手动添加两个类。
PushHub 集线器类,Singlarl类的主要操作都由这个类实现。
public class PushHub : Hub
{
/// <summary>
/// 第一次连接
/// </summary>
/// <returns></returns>
public override Task OnConnected()
{
return base.OnConnected();
} /// <summary>
/// 断开连接
/// </summary>
/// <param name="stopCalled"></param>
/// <returns></returns>
public override Task OnDisconnected(bool stopCalled)
{
string user = ConnectManager.GetUserName(Context.ConnectionId);
ConnectManager.RemoveUser(user);
Show(string.Format("{0}退出", user)); return base.OnDisconnected(stopCalled);
} /// <summary>
/// 获取当前的用户标识
/// </summary>
/// <returns></returns>
private string GetUserId()
{
return Context.QueryString["userId"];
} /// <summary>
/// 发送消息
/// </summary>
/// <param name="content"></param>
/// <param name="receiveUser"></param>
public void Show(string content,string receiveUser="")
{
string user = ConnectManager.GetUserName(Context.ConnectionId);
if (string.IsNullOrEmpty(receiveUser))
{
Clients.All.show(content);
}
else {
Clients.Client(ConnectManager.GetUserConnect(receiveUser)).show(string.Format("{0}发消息:{1}",user, content));
} } /// <summary>
/// 登录操作
/// </summary>
/// <param name="user"></param>
public void Login(string user)
{ ConnectManager.OnlineInit(user, Context.ConnectionId);
Show(string.Format("{0}:登录成功", user));
} }
4.Startup类
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR(); //声明注册集线器映射
}
}
5.连接管理类
/// <summary>
/// 连接管理类
/// </summary>
public class ConnectManager
{
/// <summary>
/// 连接记录池
/// </summary>
private readonly static ConcurrentDictionary<string, string> _connectPool = new ConcurrentDictionary<string, string>(); /// <summary>
/// 添加用户
/// </summary>
/// <param name="userKey"></param>
/// <param name="connection"></param>
public static void AddUser(string userKey, string connection)
{
_connectPool[userKey] = connection;
} /// <summary>
/// 删除用户
/// </summary>
/// <param name="userKey"></param>
public static void RemoveUser(string userKey)
{
string connection = null;
_connectPool.TryRemove(userKey, out connection);
} /// <summary>
/// 是否存在连接(是否在线)
/// </summary>
/// <param name="receiverId"></param>
/// <returns></returns>
public static bool IsOnline(string receiverId)
{
return _connectPool.Keys.Contains(receiverId);
} /// <summary>
/// 推送消息给个人
/// </summary>
/// <param name="receiveId"></param>
/// <param name="msg"></param>
public static void PushSingleMessage(string receiveId, string msg)
{
try
{
GetHubContext().Clients.Client(_connectPool[receiveId]).show(msg);
}
catch (Exception ex)
{
var errMsg = ex.Message;
}
} /// <summary>
/// 获取推送上下文
/// </summary>
/// <returns></returns>
public static IHubContext GetHubContext()
{
return GlobalHost.ConnectionManager.GetHubContext<PushHub>();
} /// <summary>
/// 上线初始化
/// </summary>
/// <param name="userId">用户ID</param>
/// <param name="connectionId">连接ID</param>
public static void OnlineInit(string userId, string connectionId)
{
AddUser(userId, connectionId);
} public static string GetUserName(string value)
{
return _connectPool.Where(a => a.Value == value).FirstOrDefault().Key;
} public static string GetUserConnect(string userName)
{
return _connectPool[userName];
}
}
6.前台代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div>
用户名称:<input type="text" id="user" placeholder="输入用户名" class="input" /><input type="button" id="login" value="登录" class="btn btn-sm btn-info" /><br />
接收人:<input type="text" id="receiveUser" placeholder="接收人(不填默认群发)" class="input" /><br />
<input type="text" id="content" placeholder="发送内容" class="input" /> <input type="button" value="发送" class="btn btn-sm btn-info" id="send" />
<div>
<h4>接收到的信息:</h4>
<ul id="dataContainer"></ul>
</div>
</div>
<script src="Scripts/jquery-3.3.1.min.js"></script>
<script src="Scripts/jquery.signalR-2.4.1.min.js"></script>
<script src="signalr/hubs"></script> ///这个要注意默认就是这样写,不要问为什么。哈哈
<script language="javascript">
$(function () {
var chat = $.connection.pushHub; console.log(chat);
//连接服务端集线器,demoHub为服务端集线器名称,js上首字母须改为小写(系统默认)
//定义客户端方法,此客户端方法必须与服务端集线器中的方法名称、参数均一致。
//实际上是服务端调用了前端的js方法(订阅)
//若多个参数,服务端也需要一致 chat.client.show = function (content) {
var html = '<li>' + htmlEncode(content) + "</li>";
$("#dataContainer").append(html);
} //定义推送
$.connection.hub.start()
.done(function () {
$("#login").click(function () {
chat.server.login($("#user").val()); //将客户端的content内容发送到服务端
$("#user").val("");
});
$("#send").click(function () {
chat.server.show($("#content").val(), $("#receiveUser").val()); //将客户端的content内容发送到服务端
$("#content").val("");
});
}); });
//编码
function htmlEncode(value) {
var encodedValue = $('<div />').text(value).html();
return encodedValue;
}
</script>
</body> </html>
这就是所有的demo的代码
demo代码:https://github.com/chaorending/Demo.SignalR.git