SignalR全套系列之在.Net Core 中实现长轮询
Posted dotNET跨平台
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SignalR全套系列之在.Net Core 中实现长轮询相关的知识,希望对你有一定的参考价值。
微信公众号:趣编程ACE
关注可了解更多的.NET日常实战开发技巧,如需源码 请后台留言 源码;
前文回顾
【SignalR全套系列】之在.Net Core 中实现Server-Send Events消息推送
【SignalR全套系列】之在.NetCore中实现WebSocket双工通信
【SignalR全套系列】之在.Net Core 中实现长轮询
客户端实现
1// 详细代码讲解 见视频
2const listen = (cb) => fetch("/listen")
3 .then(r => r.text())
4 .then(t =>
5 cb(t);
6 listen(cb);
7 );
8
9 listen((e) => console.log(e));
10
11 // fetch send("hello")
12 const send = (m) => fetch("/send?m=" + encodeURIComponent(m));
服务端实现
1// 创建一个无消息上限通道
2public Startup(IConfiguration configuration)
3
4 // ....
5 _channel = Channel.CreateUnbounded<string>();
6
7 private Channel<string> _channel;
1// 设置两个路由节点 一个是客户端 发送节点 一个是监听节点
2app.UseEndpoints(endpoints =>
3
4 endpoints.MapControllers();
5 endpoints.Map("/listen", async context =>
6
7 // 等待消息通道中有数据可读
8 if(await _channel.Reader.WaitToReadAsync())
9
10 if(_channel.Reader.TryRead(out var data))
11
12 // 读写数据 返回给客户端
13 context.Response.StatusCode = 200;
14 await context.Response.WriteAsync(data);
15 return;
16
17
18 context.Response.StatusCode = 200;
19 );
20
21 endpoints.Map("/send", async ctx =>
22
23 // /send?m=xxx
24 if(ctx.Request.Query.TryGetValue("m",out var data))
25
26 // 获取路由的查询信息
27 Trace.WriteLine("发送的消息:"+data);
28 await _channel.Writer.WriteAsync(data); // 推送到消息通道中
29
30 ctx.Response.StatusCode = 200;
31 );
以上是关于SignalR全套系列之在.Net Core 中实现长轮询的主要内容,如果未能解决你的问题,请参考以下文章
SignalR全套系列之在.Net6中实现SignalR分组通信
SignalR全套系列之在.Net6中实现SignalR分组通信