Asp.net SignalR
一、介绍
SignalR对websocket、SSE、长连接、forever frame进行封装。
websocket(html5):ws协议,这个协议基于tcp的。也就是说和http没有关系(兼容性不好)
SSE:客户端订阅服务器的一个事件,然后方便通过这个事件推送到客户端。 server => client
长链接:保持一次链接的时间,例如保持一个链接5s
forever frame:在body中藏一个iframe,那么这个iframe和server是一个永久链接,如果server来数据,通过这个链接推送到client
二、PersistentConnection
1,参数
《1》 request: 获取一些链接中的附加信息,request.querystring
request.cookie
request是一个katana的包装类。
singlaR 的request 其实是asp.net 中的 Request的子集。
《2》 connectionId 这个参数就是 客户端连接到服务器的唯一标识。。。也就说这个标识标识了客户端。本质上来说,和SessionID是一个性质。 【GUID】
2,demo
usingSystem;usingSystem.Threading.Tasks;usingMicrosoft.Owin;usingOwin;[assembly: OwinStartup(typeof(WebApplication1.Startup1))]namespaceWebApplication1 {public classStartup1{public voidConfiguration(IAppBuilder app){//For more information on how to configure your application, visithttps://go.microsoft.com/fwlink/?LinkID=316888 app.MapSignalR<MyConnection1>("/connection");}} }
Startup1
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Threading.Tasks;usingSystem.Web;usingMicrosoft.AspNet.SignalR;namespaceWebApplication1 {public classMyConnection1 : PersistentConnection{//js调用 start 触发protected override Task OnConnected(IRequest request, stringconnectionId){return Connection.Send(connectionId, "Welcome!");}//js 调用send触发protected override Task OnReceived(IRequest request, string connectionId, stringdata){returnConnection.Broadcast(data);}//关闭连接(或者浏览器窗口)触发protected override Task OnDisconnected(IRequest request, string connectionId, boolstopCalled){return base.OnDisconnected(request, connectionId, stopCalled);}} }
MyConnection1
<!DOCTYPE html> <html> <head><meta charset="utf-8" /><title></title><script src="Scripts/jquery-1.6.4.js"></script><script src="Scripts/jquery.signalR-2.2.3.js"></script><script type="text/javascript">var con = $.connection("/connection");//启动 con.start(function (data) {con.send("asdasd")})con.received(function (data) {console.log("receive:"+data)})</script> </head> <body></body> </html>
html
二、group(建简易聊天室)
usingSystem;usingSystem.Threading.Tasks;usingMicrosoft.Owin;usingOwin;[assembly: OwinStartup(typeof(WebApplication1.Startup1))]namespaceWebApplication1 {public classStartup1{public voidConfiguration(IAppBuilder app){//For more information on how to configure your application, visithttps://go.microsoft.com/fwlink/?LinkID=316888 app.MapSignalR<MyConnection1>("/connection");}} }
Startup1
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Threading.Tasks;usingSystem.Web;usingMicrosoft.AspNet.SignalR;namespaceWebApplication1 {public classMyConnection1 : PersistentConnection{private const string DEFAULT = "default";//js调用 start 触发protected override Task OnConnected(IRequest request, stringconnectionId){this.Groups.Add(connectionId, DEFAULT);//excludeConnectionIds:排除通知的connectionId。在default组中,除了自己,其他人都能收到信息return this.Groups.Send(DEFAULT, connectionId + "进入房间", connectionId);}//js 调用send触发protected override Task OnReceived(IRequest request, string connectionId, stringdata){//excludeConnectionIds:排除通知的connectionId。在default组中,除了自己,其他人都能收到信息return this.Groups.Send(DEFAULT, connectionId + ":" +data, connectionId);}//关闭连接(或者浏览器窗口)触发protected override Task OnDisconnected(IRequest request, string connectionId, boolstopCalled){return base.OnDisconnected(request, connectionId, stopCalled);}} }
MyConnection1
<!DOCTYPE html> <html> <head><meta charset="utf-8" /><title></title><script src="Scripts/jquery-1.6.4.js"></script><script src="Scripts/jquery.signalR-2.2.3.js"></script><script type="text/javascript">$(function () {var con = $.connection("/connection");//启动 con.start(function (data) {})con.received(function (data) {$("#context").append("<br/>"+data)console.log(data)})$("#send").click(function () {con.send($("#txt").val())})})</script> </head> <body><input type="text" id="txt" /><input type="button" id="send" value="发送"/><div id="context"></div></body> </html>
html
案例下载:https://pan.baidu.com/s/1YJN-bwertKNQc2O5JHlQgg
三、Hub
1,js调用直接后端方法、后端直接调用js方法
usingSystem;usingSystem.Threading.Tasks;usingMicrosoft.Owin;usingOwin;[assembly: OwinStartup(typeof(WebApplication1.Startup1))]namespaceWebApplication1 {public classStartup1{public voidConfiguration(IAppBuilder app){//For more information on how to configure your application, visithttps://go.microsoft.com/fwlink/?LinkID=316888 app.MapSignalR();}} }
Startup1
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Web;usingMicrosoft.AspNet.SignalR;namespaceWebApplication1 {public classMyHub : Hub{public voidHello(){//直接调用前端js方法Clients.All.aa("abc");}} }
Hub
<!DOCTYPE html> <html> <head><metacharset="utf-8" /><title></title><scriptsrc="Scripts/jquery-1.6.4.js"></script><scriptsrc="Scripts/jquery.signalR-2.2.3.js"></script><!--引用js--><scriptsrc="/signalr/js"></script><scripttype="text/javascript">$(function() {//启动hub $.connection.hub.start()varconne=$.connection.myHub;//申明客户端js方法 conne.client.aa= function(msg) {$("#context").append("<br/>" +msg)}$("#send").click(function() {//直接调用后端方法 conne.server.hello();})})</script> </head> <body><inputtype="text"id="txt" /><inputtype="button"id="send"value="发送"/><divid="context"></div></body> </html>
html
2,HubName/HubMethodName
using Microsoft.AspNet.SignalR.Hubs;
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Web;usingMicrosoft.AspNet.SignalR;usingMicrosoft.AspNet.SignalR.Hubs;namespaceWebApplication1 {[HubName("MyHub")]public classMyHub : Hub{[HubMethodName("Hello")]public voidHello(){//直接调用前端js方法Clients.All.aa("abc");}} }
MyHub
3,ConnectionId
this.Context.ConnectionId;
四、Hub中的clients 和 groups属性
1,Clients
①T All { get; }
相当于持久连接中的 Broadcast。
②T AllExcept(params string[] excludeConnectionIds);
给排除本人所有人发送消息。(excludeConnectionIds排除的连接id)
③T Client(string connectionId);
跟Send操作就是一样的了。
④T Clients(IList<string> connectionIds);
和Send操作的重载方法一样,可以给一批指定的人发送。
⑤T Group(string groupName, params string[] excludeConnectionIds);
给房间中的指定人发送消息: Clients.Group("room1", "asdfasdfads");
⑥T Groups(IList<string> groupNames, params string[] excludeConnectionIds);
给房间列表中的指定人发送消息; 【天然的聊天室功能】
⑦T User(string userId);
这个和Client是有区别的。 这个userId => this.Context.Request.User.Identity.Name 【form验证】
cookie中间件来做到singlar的身份验证。
userId 是你自己定义的一个标识。
T Users(IList<string> userIds);
2,Groups
①Task Add(string connectionId, string groupName);
向组内添加链接
②Task Remove(string connectionId, string groupName);
删除组内的连接
五、GlobalHost
1,获取Hub的上下文
var hub = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
2,对singlar的全局设置
GlobalHost.Configuration.MaxIncomingWebSocketMessageSize:
websocket模式下,消息的传输大小,如果大于默认的64k,那么就会出问题。
GlobalHost.Configuration.DisconnectTimeout:
websocket强制关闭的时间。 30 seconds
GlobalHost.Configuration.TransportConnectTimeout:
传输的超时时间。 5s
六、生成代理js
下载安装nuget: Microsoft.AspNet.SignalR.Utils
1,模板:signalr.exe ghp /path:《..\bin》 /o:《..\hub.js》
2,案例:
C:\Users\Hunter\Desktop\ConsoleApp3\packages\Microsoft.AspNet.SignalR.Utils.2.2.3\tools>signalr.exe ghp /path:C:\Users\Hunter\Desktop\ConsoleApp3\WebApplication2\bin /o:C:\Users\Hunter\Desktop\ConsoleApp3\WebApplication2\Scripts\hub.js
3,编译命令:
$(SolutionDir)packages\Microsoft.AspNet.SignalR.Utils.2.2.3\tools\signalr.exe ghp /path:$(SolutionDir)$(ProjectName)\$(OutDir) /o:$(SolutionDir)$(ProjectName)\Scripts\hub.js
4,替换代理js
七、支持跨域
①下载安装nuget: Microsoft.Owin.Cors
②配置项
usingSystem;usingSystem.Threading.Tasks;usingMicrosoft.Owin;usingOwin;usingMicrosoft.AspNet.SignalR;usingMicrosoft.Owin.Cors;[assembly: OwinStartup(typeof(WebApplication2.Startup))]namespaceWebApplication2 {public classStartup{public voidConfiguration(IAppBuilder app){//For more information on how to configure your application, visithttps://go.microsoft.com/fwlink/?LinkID=316888 app.UseCors(CorsOptions.AllowAll);app.MapSignalR();}} }
Startup
③生成代理js
④修改代理js
⑤html
<!DOCTYPE html> <html> <head><metacharset="utf-8" /><title></title><scriptsrc="Scripts/jquery-1.6.4.js"></script><scriptsrc="Scripts/jquery.signalR-2.2.3.js"></script><!--引用js--><!--<script src="/signalr/js"></script>--><scriptsrc="Scripts/hub.js"></script><scripttype="text/javascript">$(function() {//启动hub $.connection.hub.start()varconne=$.connection.myHub;//申明客户端js方法 conne.client.aa= function(msg) {$("#context").append("<br/>" +msg)}$("#send").click(function() {//直接调用后端方法 conne.server.hello();})})</script> </head> <body><inputtype="text"id="txt" /><inputtype="button"id="send"value="发送"/><divid="context"></div></body> </html>
html
案例下载:https://pan.baidu.com/s/1GY_Io63qZeECbGbEH589fg
八、集群部署
使用redis:
nuget: Microsoft.AspNet.SignalR.Redis
usingSystem;usingSystem.Threading.Tasks;usingMicrosoft.Owin;usingOwin;usingMicrosoft.AspNet.SignalR;usingMicrosoft.Owin.Cors;[assembly: OwinStartup(typeof(WebApplication2.Startup))]namespaceWebApplication2 {public classStartup{public voidConfiguration(IAppBuilder app){//For more information on how to configure your application, visithttps://go.microsoft.com/fwlink/?LinkID=316888//使用redis做底板GlobalHost.DependencyResolver.UseRedis("localhost", 6379,string.Empty, "mykey");app.UseCors(CorsOptions.AllowAll);app.MapSignalR();}} }
Startup
九、将singlar.exe 装入到 性能监视器
signlar.exe ipc 命令来安装性能监视器 [install performance counters]
signlar.exe upc 来卸载性能监视器 [uninstall performance counters]
十、HubPipeLine管道
实现:IHubPipelineModule
①入流: BuildIncoming 监控
②出流: BuildOutgoing 监控
转载于:https://www.cnblogs.com/zd1994/p/8902570.html
Asp.net SignalR相关推荐
- Asp.net SignalR 应用并实现群聊功能 开源代码
ASP.NET SignalR 是为 ASP.NET 开发人员提供的一个库,可以简化开发人员将实时 Web 功能添加到应用程序的过程.实时 Web 功能是指这样一种功能:当所连接的客户端变得可用时服务 ...
- Asp.net SignalR 实现服务端消息推送到Web端
参考博客https://www.cnblogs.com/wintersun/p/4148223.html ASP .NET SignalR是一个ASP .NET 下的类库,可以在ASP .NET 的W ...
- ASP.NET SignalR增加Azure支持
在过去几年里,微软一直在开发两种形式的SignalR--原先的ASP.NET SignalR库和新的ASP.NET Core SignalR.来自微软的Andrew Stanton-Nurse最近分享 ...
- [Asp.net]SignalR实现实时日志监控
摘要 昨天吃饭的时候,突然想起来一个好玩的事,如果能有个页面可以实时的监控网站或者其他类型的程序的日志,其实也不错.当然,网上也有很多成熟的类似的监控系统.就想着如果通过.net该如何实现?所以就在想 ...
- C# -Asp.Net.SignalR.Core之Hub
前言 程序员的进步是需要环境的,良好的团队环境,良好的开发环境,会让人进步的更加快速. 所以,我认为,如果一个程序员,在2019年还在用Visual Studio 2005开发,那么,他,大概率,不会 ...
- ASP.NET SignalR 与 LayIM2.0 配合轻松实现Web聊天室(一) 之 基层数据搭建,让数据活起来(数据获取)...
大家好,本篇是接上一篇 ASP.NET SignalR 与 LayIM2.0 配合轻松实现Web聊天室(零) 前言 ASP.NET SignalR WebIM系列第二篇.本篇会带领大家将 LayIM ...
- LayIM 3.9.1与ASP.NET SignalR实现Web聊天室快速入门(五)之使用RabbitMQ缓存消息
前言 本系列文章特点:使用ASP.NET SignalR和LayIM快速入门对接,实现一对一聊天,群聊,添加聊天群组,查找聊天记录等功能.源代码不包含LayIM的源代码,因为官方并没开源属于收费资源, ...
- ASP.NET SignalR 与 LayIM2.0 配合轻松实现Web聊天室(五) 之 加好友,加群流程,消息管理和即时消息提示的实现...
前言 前前一篇留了个小问题,在上一篇中忘了写了,就是关于LayIM已经封装好的上传文件或者图片的问题.对接好接口之后,如果上传速度慢,界面就会出现假死情况,虽然文件正在上传.于是我就简单做了个图标替代 ...
- LayIM 3.9.1与ASP.NET SignalR实现Web聊天室快速入门(七)之LayIM与MVC数据交互实现单聊和群聊
前言 本系列文章特点:使用ASP.NET SignalR和LayIM快速入门对接,实现一对一聊天,群聊,添加聊天群组,查找聊天记录等功能.源代码不包含LayIM的源代码,因为官方并没开源属于收费资源, ...
- LayIM 3.9.1与ASP.NET SignalR实现Web聊天室快速入门(四)之ASP.NET SignalR核心功能介绍
前言 本系列文章特点:使用ASP.NET SignalR和LayIM快速入门对接,实现一对一聊天,群聊,添加聊天群组,查找聊天记录等功能.源代码不包含LayIM的源代码,因为官方并没开源属于收费资源, ...
最新文章
- 正则表达式中$1,$2 ===算是什么意思
- IJ 自动生成构造方法
- vue3中ref、reactive、shallowRef、 shallowReactive、toRaw、unref、toRef、toRefs、customRef使用与区别
- C++学习之路 | PTA乙级—— 1009 说反话 (20分)(精简)
- python之---子类父类属性之间的关系
- python实现卷积神经网络_【455】Python 徒手实现 卷积神经网络 CNN
- 伺服电机算功率基本公式_伺服电机选型通用计算公式
- 游戏,CG音乐音效配音
- python天眼查 的融资_python怎么爬取天眼查工商基本信息?
- java导出帆软pdf,java后台把fineRepo图表导出pdf格式时发生错误!
- 超级经典回帖专用语(转载)
- epub.js制作电子书阅读网站
- h5唤醒软键盘(数字键盘)
- 2021年9款优秀的大数据可视化BI软件
- Python语法小白入门
- 融云根据关键字获取搜索聊天记录
- 四级语法4——定语从句
- 图论:图的四种最短路径算法
- isspace() 函数
- listview 和RecycleView区别
热门文章
- Python 2.x 即将终止支持,是时候和 Python 2 讲再见了
- vue webapp滑动事件_js_监听移动端web触屏事件_滑动响应
- 决策树缺失值python_【机器学习笔记之二】决策树的python实现
- linux ls 时间显示时间格式,ls -l显示的日期格式如何设定?
- svn回退后如何再还原_设计师如何管理自己的文档
- CentOS下安装Tomcat并配置JRE
- linux docker run怎么退出,详解如何进入、退出docker容器的方法
- java过滤器解决乱码_[java]如何使用过滤器解决jsp乱码
- oracle数据库实践,RubyonRails连接Oracle数据库实践
- java错误页面_java自定义错误页面实现方法