Asp.net core中的websocket

简介:




Websockethtml5后的产物,对于asp.net core中也得到了支持,首先在NuGet中添加Microsoft.AspNetCore.WebSockets的引用(现在是1.0.1版本,201737日发布的)。

首先在Configure中添加中间件

1
2
//添加websocket中间件
app.UseWebSockets();

接下来就要定义自己处理websocket的中间件了,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
using  Microsoft.AspNetCore.Http;
using  System;
using  System.Net.WebSockets;
using  System.Threading;
using  System.Threading.Tasks;
  
namespace  Asp.NetCore_WebPage.Middleware
{
     /// <summary>
     /// websocket中间件,客户端发送的信息显示在控件台上,客户端会定时收到服务端推送的时间
     /// </summary>
     public  class  WebSocketNotifyMiddleware
     {
         /// <summary>
         /// 管道代理对象
         /// </summary>
         private  readonly  RequestDelegate _next;
         /// <summary>
         /// 
         /// </summary>
         /// <param name="next"></param>
         public  WebSocketNotifyMiddleware(RequestDelegate next)
         {
             _next = next;
         }
         /// <summary>
         /// 中间件调用
         /// </summary>
         /// <param name="context"></param>
         /// <returns></returns>
         public  Task Invoke(HttpContext context)
         {
             //判断是否为websocket请求
             if  (context.WebSockets.IsWebSocketRequest)
             {
                 //接收客户端
                 var  webSocket = context.WebSockets.AcceptWebSocketAsync().Result;
                 //启用一个线程处理接收客户端数据
                 new  Thread(Accept).Start(webSocket);
                 while  (webSocket.State == WebSocketState.Open)
                 {
                     webSocket.SendAsync( new  ArraySegment< byte >(System.Text.Encoding.UTF8.GetBytes($ "{DateTime.Now}" )), System.Net.WebSockets.WebSocketMessageType.Text,  true , CancellationToken.None);
                     Thread.Sleep(1000);
                 }
             }
             return  this ._next(context);
  
         }
         /// <summary>
         /// 接收客户端数据方法,这里可以根据自己的需求切换功能代码
         /// </summary>
         /// <param name="obj"></param>
         void  Accept( object  obj)
         {
             var  webSocket = obj  as  WebSocket;
             while  ( true )
             {
                 var  acceptArr =  new  byte [1024];
  
                 var  result = webSocket.ReceiveAsync( new  ArraySegment< byte >(acceptArr), CancellationToken.None).Result;
  
                 var  acceptStr = System.Text.Encoding.UTF8.GetString(acceptArr).Trim( char .MinValue);
                 Console.WriteLine( "收到信息:"  + acceptStr);
             }
  
         }
     }
}

添加中间件扩展

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
using  Microsoft.AspNetCore.Builder;
using  Microsoft.AspNetCore.Http;
using  System;
using  System.Collections.Generic;
using  System.Linq;
using  System.Net.WebSockets;
using  System.Threading;
using  System.Threading.Tasks;
  
namespace  Asp.NetCore_WebPage.Middleware
{
     /// <summary>
     /// websocket通知中间件扩展
     /// </summary>
     public  static  class  WebSocketNotifyMiddlewareExtensions
     {
         /// <summary>
         /// 使用websocket通知
         /// </summary>
         /// <param name="builder"></param>
         /// <returns></returns>
         public  static  IApplicationBuilder UseWebSocketNotify(
           this  IApplicationBuilder builder)
         {
             return  builder.UseMiddleware<WebSocketNotifyMiddleware>();
         }
     }
}

这样,就可以在Startup.cs中的Configure中添加自己创建的中间件了,代码如下:

1
2
3
//添加websocket中间件
  app.UseWebSockets();
  app.UseWebSocketNotify();


到此服务端创建完成,接下来看客户端:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<div>
     当前在数据:<div id= "message" ></div>
     <div id= "output" ></div>
     <input class= "form-control"  type= "text"  id= "sendtxt"  value= "测试"  />
     <input type= "button"  onclick= "start()"  value= "开始"  />
     <input type= "button"  onclick= "send()"  value= "发送"  />
</div>
@section scripts{
<script>
var  socket;
      var  uri =  "ws://localhost:5000/ws" ;
//初始化连接
function  doConnect(open, accept, close, error) {
console.log( "doConnect" )
//创建websocket,并定义事件回调
     socket =  new  WebSocket(uri);
     socket.onopen =  function  (e) { open();};
     socket.onclose =  function  (e) { close(); };
     socket.onmessage =  function  (e) {
         accept(e.data);
     };
     socket.onerror =  function  (e) { error(e.data); };
}
//发送信息
function  doSend(message) {
     console.log( "doSend" )
     socket.send(message);
}
//关闭socket
function  doClose() {
     console.log( "doClose" )
     socket.close();
}        
//打开连接回调
         function  open() {
             console.log( "open" )
             document.getElementById( "message" ).innerText =  "连接打开" ;
         }
         //接收数据回调
         function  accept(result) {
             console.log( "accept" )
             document.getElementById( "output" ).innerText=result;
         }
         //关闭连接回调
         function  close() {
             console.log( "close" )
             document.getElementById( "message" ).innerText= "连接关闭" ;
         } //错误回调
         function  error(result) {
             console.log( "error" )
             alert( "错误:" +result);
         }
         //开始方法
         function  start() {
             console.log( "start" )
             doConnect(open, accept, close, error);         
         }
         function  send()
         {
             console.log( "send" )
             doSend(document.getElementById( "sendtxt" ).value); 
         }
     </script>
}


这里只是一个基本的例子,可以根据自己的业务来实现不同的功能。

















本文转自桂素伟51CTO博客,原文链接:http://blog.51cto.com/axzxs/1909795 ,如需转载请自行联系原作者



相关文章
|
1月前
|
Cloud Native API C#
C#的现代化:.NET Core引领的技术革命
【6月更文挑战第9天】`.NET Core引领C#现代化,实现跨平台革命,提升性能并支持云原生应用。异步编程模型优化体验,统一API简化开发流程。C#应用场景扩展,开发效率提高,技术创新加速,预示其未来在技术领域将持续发挥关键作用。`
38 10
|
18天前
|
开发框架 .NET API
.NET Core 和 .NET 标准类库项目类型有什么区别?
在 Visual Studio 中,可创建三种类库:.NET Framework、.NET Standard 和 .NET Core。.NET Standard 是规范,确保跨.NET实现的API一致性,适用于代码共享。.NET Framework 用于特定技术,如旧版支持。.NET Core 库允许访问更多API但限制兼容性。选择取决于兼容性和所需API:需要广泛兼容性时用.NET Standard,需要更多API时用.NET Core。.NET Standard 替代了 PCL,促进多平台共享代码。
|
25天前
|
开发框架 JSON .NET
|
28天前
|
开发框架 .NET Nacos
使用 Nacos 在 C# (.NET Core) 应用程序中实现高效配置管理和服务发现
使用 Nacos 在 C# (.NET Core) 应用程序中实现高效配置管理和服务发现
70 0
|
1月前
|
存储 JSON NoSQL
技术心得记录:在.NETCore中使用CSRedis
技术心得记录:在.NETCore中使用CSRedis
20 0
|
1月前
|
SQL 开发框架 .NET
(20)ASP.NET Core EF创建模型(必需属性和可选属性、最大长度、并发标记、阴影属性)
(20)ASP.NET Core EF创建模型(必需属性和可选属性、最大长度、并发标记、阴影属性)
|
1月前
|
开发框架 .NET Linux
【.NET Developer】已发布好的.NET Core项目文件如何打包为Docker镜像文件
该文介绍了如何不使用VS2019手动创建ASP.NET Core Blazor项目的Dockerfile并构建Docker镜像。首先,创建名为Dockerfile的文件,并复制提供的Dockerfile内容,该文件指定了基础镜像和工作目录。然后,通过CMD在项目目录下运行`docker build -t 自定义镜像名 .`来生成镜像。最后,使用`docker run`命令启动容器并验证项目运行。此外,文章还提到了将镜像推送到Azure Container Registry (ACR)的步骤。
|
开发框架 .NET 中间件
ASP.NET Core 面试题(二)
ASP.NET Core 面试题(二)
296 0
|
开发框架 JSON .NET
ASP.NET Core 面试题(一)
ASP.NET Core 面试题(一)
928 0
|
2月前
|
开发框架 前端开发 .NET
ASP.NET CORE 3.1 MVC“指定的网络名不再可用\企图在不存在的网络连接上进行操作”的问题解决过程
ASP.NET CORE 3.1 MVC“指定的网络名不再可用\企图在不存在的网络连接上进行操作”的问题解决过程
118 0