【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 });