微信公眾號:趣編程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));
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????????????????});