当前位置:首页 >> 智能终端演进 >> 【SignalR全套系列】之在.Net Core 中实现长轮询,hp dv1000

【SignalR全套系列】之在.Net Core 中实现长轮询,hp dv1000

cpugpu芯片开发光刻机 智能终端演进 1
文件名:【SignalR全套系列】之在.Net Core 中实现长轮询,hp dv1000 【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            });89        listen((e) => console.log(e));1011        // 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                 });2021                endpoints.Map("/send", async ctx => 22                {23                    //   /send?m=xxx24                    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                });
协助本站SEO优化一下,谢谢!
关键词不能为空
同类推荐
«    2025年12月    »
1234567
891011121314
15161718192021
22232425262728
293031
控制面板
您好,欢迎到访网站!
  查看权限
网站分类
搜索
最新留言
文章归档
网站收藏
友情链接