使用SuperWebSocket实现Web消息推送
在大部分Web系统中,我们可能遇到需要向客户端推送消息的需求。SuperWebSocket第三方库能让我们轻松的完成任务。SuperWebSocket第三方库可以从网上下载,不过通过Visual Studio Nuget安装更快。

引用SuperWebSocket相关组件后,在项目中添加WebSocketManager类
using SuperWebSocket;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks; namespace WebSocketDemo
{
public static class WebSocketManager
{
static Dictionary<string, WebSocketSession> sessionDics = new Dictionary<string, WebSocketSession>();
static WebSocketServer webSocketServer;
public static void Init()
{
var ip = GetLocalIP();
webSocketServer = new WebSocketServer(); var isSetup = webSocketServer.Setup(ip, );
Common.LogHelper.WriteError("WebSocketManager: 服务器端启动" + (isSetup ? "成功" : "失败"));
if (!isSetup)
return; webSocketServer.NewSessionConnected += WebSocketServer_NewSessionConnected;
webSocketServer.SessionClosed += WebSocketServer_SessionClosed;
webSocketServer.NewMessageReceived += WebSocketServer_NewMessageReceived; var isStart = webSocketServer.Start();
Common.LogHelper.WriteError("WebSocketManager: 服务器端侦听" + (isStart ? "成功" : "失败"));
} /// <summary>
/// 接收消息
/// </summary>
/// <param name="session"></param>
/// <param name="value"></param>
private static void WebSocketServer_NewMessageReceived(WebSocketSession session, string value)
{
Common.LogHelper.WriteError("WebSocketManager: 接收消息 \r\n" + value); if (!string.IsNullOrWhiteSpace(value))
{
if (!sessionDics.ContainsKey(value))
sessionDics.Add(value, session);
else
sessionDics[value] = session; }
} /// <summary>
/// 下线
/// </summary>
/// <param name="session"></param>
/// <param name="value"></param>
private static void WebSocketServer_SessionClosed(WebSocketSession session, SuperSocket.SocketBase.CloseReason value)
{
Common.LogHelper.WriteError(string.Format("WebSocketManager:{0} {1}下线", value, session.RemoteEndPoint));
} /// <summary>
/// 上线
/// </summary>
/// <param name="session"></param>
private static void WebSocketServer_NewSessionConnected(WebSocketSession session)
{
Common.LogHelper.WriteError(string.Format("WebSocketManager:{0}上线",session.RemoteEndPoint));
} /// <summary>
/// 发送消息到客户端
/// </summary>
/// <param name="value"></param>
/// <param name="msg"></param>
public static void SendMsgToRemotePoint(string value, string msg)
{
if (sessionDics.ContainsKey(value))
{
var webSocketSession = sessionDics[value];
if (webSocketSession != null)
{
webSocketSession.Send(msg);
}
}
} /// <summary>
/// 获取本地IP等信息
/// </summary>
/// <returns></returns>
public static string GetLocalIP()
{
//本机IP地址
string strLocalIP = "";
//得到计算机名
string strPcName = Dns.GetHostName();
//得到本机IP地址数组
IPHostEntry ipEntry = Dns.GetHostEntry(strPcName);
//遍历数组
foreach (var IPadd in ipEntry.AddressList)
{
//判断当前字符串是否为正确IP地址
if (IsRightIP(IPadd.ToString()))
{
//得到本地IP地址
strLocalIP = IPadd.ToString();
//结束循环
break;
}
} //返回本地IP地址
return strLocalIP;
}
/// <summary>
/// 判断是否为正确的IP地址
/// </summary>
/// <param name="strIPadd">需要判断的字符串</param>
/// <returns>true = 是 false = 否</returns>
private static bool IsRightIP(string strIPadd)
{
//利用正则表达式判断字符串是否符合IPv4格式
if (Regex.IsMatch(strIPadd, "[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}"))
{
//根据小数点分拆字符串
string[] ips = strIPadd.Split('.');
if (ips.Length == || ips.Length == )
{
//如果符合IPv4规则
if (System.Int32.Parse(ips[]) < && System.Int32.Parse(ips[]) < & System.Int32.Parse(ips[]) < & System.Int32.Parse(ips[]) < )
//正确
return true;
//如果不符合
else
//错误
return false;
}
else
//错误
return false;
}
else
//错误
return false;
}
}
}
在Global.asax.cs下初始化WebSocket,并启动。
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles); WebSocketManager.Init();
}
}
前端连接服务端WebSocket,打开网页调用此js方法,就可以和服务端建立长连接通信。
WebSocketConnent(){
var ip= localStorage.getItem("IP");//服务端的IP
var openId= localStorage.getItem("kmWechatOpenId");//value
var url="ws://"+ip+":2019";
var ws;
if ("WebSocket" in window) {
ws = new WebSocket(url);
}
else if ("MozWebSocket" in window) {
ws = new MozWebSocket(url);
}
else{
console.log("WebSocketConnent","浏览器版本过低,请升级您的浏览器")
}
//注册各类回调
ws.onopen = function () {
ws.send(openId);//服务端WebSocketServer_NewMessageReceived 接收到消息
console.log("WebSocketConnent","连接服务器成功");
}
ws.onclose = function () {
console.log("WebSocketConnent","与服务器断开连接");
}
ws.onerror = function () {
console.log("WebSocketConnent","数据传输发生错误");
}
ws.onmessage = function (receiveMsg) {
localStorage.removeItem("token");//服务端SendMsgToRemotePoint 发送消息后接收
console.log("WebSocketConnent","服务器推送过来的消息:"+receiveMsg.data);
}
},
使用SuperWebSocket实现Web消息推送的更多相关文章
- WEB消息推送-框架篇
WEB消息推送-comet4j 一.comet简介: comet :基于 HTTP长连接的“服务器推”技术,是一种新的 Web 应用架构.基于这种架构开发的应用中,服务器端会主动以异步的方式向客户端程 ...
- 实现web消息推送的技术和采用长轮询corundumstudio介绍
实时消息的推送,PC端的推送技术可以使用socket建立一个长连接来实现.传统的web服务都是客户端发出请求,服务端给出响应.但是现在直观的要求是允许特定时间内在没有客户端发起请求的情况下服务端主动推 ...
- web消息推送-goesay
原文:http://www.upwqy.com/details/22.html 1 GoEasy简介: GoEasy - Web实时消息推送服务专家 最简单的方式将消息从服务器端推送至客户端 最简单的 ...
- WEB消息推送-原理篇
这篇文章主要讲述B/S架构中服务器“推送”消息给浏览器.内容涉及ajax论询(polling),comet(streaming,long polling).后面会附上源代码. 最近在工作有这么一个需求 ...
- SSM项目使用GoEasy 实现web消息推送服务
一.背景 之前项目需要做一个推送功能,最开始我用websocket实现我的功能.使用websocket的好处是免费自主开发,但是有几个问题:1)浏览器的兼容问题,尤其是低版本的ie:2)因为是推送 ...
- web消息推送的各种解决办法
摘要 在各种BS架构的应用程序中,往往都希望服务端能够主动地向客户端推送各种消息,以达到类似于邮件.消息.待办事项等通知. 往BS架构本身存在的问题就是,服务器一直采用的是一问一答的机制.这就意味着如 ...
- Web消息推送框架windows部署实践
一.官方下载地址:https://www.workerman.net/web-sender 二.解压至任意目录下,双击start_for_win.bat,效果如下图: 三.打开Chrome浏览器访问: ...
- WEB消息推送-comet4j
一.comet简介: comet :基于 HTTP长连接的“服务器推”技术,是一种新的 Web 应用架构.基于这种架构开发的应用中,服务器端会主动以异步的方式向客户端程序推送数据,而不需要客户端显式的 ...
- 关于php使用基于socket Web消息推送(未完)
转:http://blog.csdn.net/young_phper/article/details/52441143 http://www.workerman.net/ http://blog.cs ...
随机推荐
- AtCoder Regular Contest 094 D Worst Case【思维题】
https://arc094.contest.atcoder.jp/tasks/arc094_b 题意: 在2次超多人的比赛中,你取得的成绩依次为第A名和第B名.一个人的成绩为a和b时,当且仅当ab& ...
- BasicAuth memo
string authInfo = userName + ":" + userPassword; authInfo = Convert.ToBase64String(Encodin ...
- PyTorch代码调试利器: 自动print每行代码的Tensor信息
本文介绍一个用于 PyTorch 代码的实用工具 TorchSnooper.作者是TorchSnooper的作者,也是PyTorch开发者之一. GitHub 项目地址: https://github ...
- sqlserver 序号重新计算
DBCC CHECKIDENT('leshua_TradeData',NORESEED) DBCC CHECKIDENT('表名',NORESEED)
- vscode golang vue配置
{ "files.autoSave": "off", "window.title": "${dirty}${activeEdito ...
- Ubuntu 14.04 使用ntfs-config解决开机自动挂载NTFS分区的方法
先安装: sudo apt-get install ntfs-3g ntfs-config 再配置一下: sudo ntfs-config 然后就会弹出来一个对话框,选择你需要挂载的分区,点应用,再选 ...
- H3C 10BASE-T线缆和接口
- H3C 配置RIP peer
- Codeforces Round #529 (Div. 3) E. Almost Regular Bracket Sequence(思维)
传送门 题意: 给你一个只包含 '(' 和 ')' 的长度为 n 字符序列s: 给出一个操作:将第 i 个位置的字符反转('(' ')' 互换): 问有多少位置反转后,可以使得字符串 s 变为&quo ...
- java Scanner(简单文本扫描器)
Scanner(File source) 构造一个新的 Scanner,它生成的值是从指定文件扫描的. 备注:实现了Iterable接口 package june6D; import java. ...