Azure Web PubSub Service:.NET Framework 4.8客户端消息接收处理咨询
问题场景
我们基于.NET Framework 4.8使用Azure Web PubSub Service,服务端能正常向客户端发送消息,但无法接收并处理客户端发来的消息,想知道是否有类似OnMessage/OnMessageReceived的事件机制,以及如何实现客户端消息的服务端处理。
当前服务端代码(仅能发送消息):
using Azure.Messaging.WebPubSub; using System; using System.Threading.Tasks; namespace pubsubservice { internal class Program { private const string cs = "Endpoint=https://mypubsub.webpubsub.azure.com;AccessKey=MyKey;Version=1.0;"; private const string hub = "Hub"; static void Main(string[] args) { var serviceClient = new WebPubSubServiceClient(cs, hub); Console.WriteLine("Server is running..."); serviceClient.SendToAll("Hello"); Console.WriteLine("\n Server - Type 'exit' to exit.\n"); var msg = Console.ReadLine(); } } }
客户端已成功建立WebSocket连接并能收发数据,但服务端无感知客户端发送的消息。
解决方案
Azure Web PubSub Service本身不提供直接的OnMessage事件监听,需通过上游(Upstream)回调机制实现客户端消息的服务端处理:Azure会把客户端发送的消息、连接状态变更等事件推送到你指定的服务端接口,由你的服务端接收并处理。
步骤1:配置Azure Web PubSub上游终结点
- 登录Azure门户,进入你的Web PubSub资源
- 左侧导航栏选择设置 > 上游
- 添加上游终结点:
- 终结点类型选
URL,填入你的.NET Framework服务的HTTP接口地址(本地测试可用http://localhost:xxxx/api/WebPubSub/ReceiveClientMessage,生产环境需用公网可访问地址) - 勾选需要推送的事件:至少勾选
message(如需监听连接/断开事件,可额外勾选connect/disconnect) - 保存配置
- 终结点类型选
步骤2:在.NET Framework服务中实现消息接收接口
方案1:ASP.NET Web API接口
如果你的服务端是Web项目,可创建Web API接口接收消息:
using System.Web.Http; using Newtonsoft.Json.Linq; using Azure.Messaging.WebPubSub; namespace PubSubService.Controllers { public class WebPubSubController : ApiController { private const string ConnectionString = "Endpoint=https://mypubsub.webpubsub.azure.com;AccessKey=MyKey;Version=1.0;"; private const string HubName = "Hub"; [HttpPost] public IHttpActionResult ReceiveClientMessage(JObject request) { // 解析Azure推送的消息 var eventType = request["eventType"]?.ToString(); var connectionId = request["connectionId"]?.ToString(); var messageContent = request["data"]?.ToString(); if (eventType == "message" && !string.IsNullOrEmpty(messageContent)) { Console.WriteLine($"收到连接[{connectionId}]的消息:{messageContent}"); // 可选:回复该客户端 var serviceClient = new WebPubSubServiceClient(ConnectionString, HubName); serviceClient.SendToConnection(connectionId, $"已收到你的消息:{messageContent}").Wait(); } return Ok(); } } }
方案2:控制台程序HTTP监听
如果是控制台服务,可使用HttpListener实现简单HTTP服务接收消息:
using System; using System.Net; using System.IO; using Newtonsoft.Json.Linq; using Azure.Messaging.WebPubSub; namespace pubsubservice { internal class Program { private const string cs = "Endpoint=https://mypubsub.webpubsub.azure.com;AccessKey=MyKey;Version=1.0;"; private const string hub = "Hub"; private static HttpListener _listener; static void Main(string[] args) { // 启动HTTP监听 StartHttpListener("http://localhost:8080/api/receive"); var serviceClient = new WebPubSubServiceClient(cs, hub); Console.WriteLine("Server is running..."); serviceClient.SendToAll("Hello"); Console.WriteLine("\n Server - Type 'exit' to exit.\n"); while (Console.ReadLine() != "exit") ; _listener.Stop(); } private static void StartHttpListener(string prefix) { _listener = new HttpListener(); _listener.Prefixes.Add(prefix); _listener.Start(); Console.WriteLine($"HTTP listener started at {prefix}"); // 异步处理请求 _listener.BeginGetContext(new AsyncCallback(HandleRequest), _listener); } private static void HandleRequest(IAsyncResult result) { var listener = (HttpListener)result.AsyncState; var context = listener.EndGetContext(result); var request = context.Request; var response = context.Response; // 读取请求内容 using (var reader = new StreamReader(request.InputStream, request.ContentEncoding)) { var requestBody = reader.ReadToEnd(); var requestObj = JObject.Parse(requestBody); var eventType = requestObj["eventType"]?.ToString(); var connectionId = requestObj["connectionId"]?.ToString(); var messageContent = requestObj["data"]?.ToString(); if (eventType == "message") { Console.WriteLine($"收到连接[{connectionId}]的消息:{messageContent}"); // 回复客户端 var serviceClient = new WebPubSubServiceClient(cs, hub); serviceClient.SendToConnection(connectionId, $"已处理你的消息:{messageContent}").Wait(); } } // 返回成功响应 response.StatusCode = (int)HttpStatusCode.OK; response.Close(); // 继续监听下一个请求 listener.BeginGetContext(new AsyncCallback(HandleRequest), listener); } } }
步骤3:测试验证
- 启动你的.NET Framework服务(本地测试需用ngrok等工具暴露端口,将ngrok提供的公网地址配置到Azure上游)
- 启动客户端发送消息
- 服务端控制台会打印收到的客户端消息,同时客户端会收到服务端的回复
内容的提问来源于stack exchange,提问作者KD2ND
相关产品推荐
相关产品推荐

