【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();
6}
7   private Channel _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                });

你可能感兴趣的:(websocket,socket,netty,webgl,中间件)