向群组发送消息的信号

问题描述 投票:0回答:1

我正在编写一个 Excel 插件来通过 SignalR 接收消息,并向群组广播消息。我的后端功能和前端在不使用组的情况下正常工作。但当我添加组后,它不起作用。对于我的后端,我有一个 AddToGroup 函数:

[Function("AddToGroup")]
[SignalROutput(HubName = "chatHub", ConnectionStringSetting = "AzureSignalRConnectionString")]
public static async Task<SignalRGroupAction> AddToGroup([HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestData req, FunctionContext context)
{
    var logger = context.GetLogger("AddToGroup");
    try
    {
        string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
        var data = JsonConvert.DeserializeObject<AddToGroupData>(requestBody);
        logger.LogInformation($"Request Data: UserId = {data.UserId}, GroupName = {data.GroupName}");

        return new SignalRGroupAction(SignalRGroupActionType.Add)
        {
            UserId = data.UserId,
            GroupName = data.GroupName
        };
    }
    catch (Exception ex)
    {
        logger.LogError($"Exception occurred in AddToGroup: {ex.Message}");
        throw;
    }
}

对于我的前端,我正在与这部分进行通信:

connection.start()
    .then(() => {
        console.log("Connected to SignalR hub.");
        // After connection, join the group
        fetch("http://localhost:7146/api/AddToGroup", { 
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({ 
            UserId: connection.connectionId, 
            GroupName: "Group1", 
          }),
        })
        .then(response => response.json())
        .then(data => console.log("Joined group", data))
        .catch(error => console.error("Error joining group", error));
      })
    .catch(err => console.error('Error during connection: ', err));

但是当我测试我的代码时,它只显示“已加入组 Group1”。但是当我发送消息时,Excel 中的任务窗格上没有显示消息。可能是什么问题?

我尝试过connection.invoke方法,但完全不起作用。

azure signalr azure-signalr
1个回答
0
投票

但是当我发送消息时,Excel 中的任务窗格上没有显示消息。可能是什么问题?

加入 SignalR 组通常不会像标准 HTTP 请求那样返回数据。相反,它可能只是表明成功或失败。您的服务器端函数

AddToGroup
返回
SignalRGroupAction
,但客户端将其视为 JSON。

  • 在这里,我有一个托管在 Azure Functions 中的 SignalR 中心,可以使用组成功连接和接收消息。

ChatHub.cs:

using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;

public class ChatHub : Hub
{
    public async Task AddToGroup(string groupName)
    {
        await Groups.AddToGroupAsync(Context.ConnectionId, groupName);
    }

    public async Task SendMessageToGroup(string groupName, string message)
    {
        await Clients.Group(groupName).SendAsync("ReceiveMessage", message);
    }
}

服务器端代码(Azure功能):

[Function("AddToGroup")]
[SignalROutput(HubName = "chatHub", ConnectionStringSetting = "AzureSignalRConnectionString")]
public static async Task<SignalRGroupAction> AddToGroup([HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestData req, FunctionContext context)
{
    var logger = context.GetLogger("AddToGroup");
    try
    {
        string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
        var data = JsonConvert.DeserializeObject<AddToGroupData>(requestBody);
        logger.LogInformation($"Request Data: UserId = {data.UserId}, GroupName = {data.GroupName}");

        return new SignalRGroupAction(SignalRGroupActionType.Add)
        {
            UserId = data.UserId,
            GroupName = data.GroupName
        };
    }
    catch (Exception ex)
    {
        logger.LogError($"Exception occurred in AddToGroup: {ex.Message}");
        throw;
    }
}

客户端代码(Excel 插件):

var connection = new signalR.HubConnectionBuilder()
   .withUrl("https://your-api-url/chatHub")
   .configureLogging(signalR.LogLevel.Information)
   .build();

connection.on('ReceiveMessage', function (message) {
   console.log('Received message:', message);
   // Process and display the received message in your Excel task pane
});

connection.start()
   .then(function () {
       console.log('Connected to SignalR hub.');
       // Join the group
       connection.invoke('AddToGroup', 'Group1')
           .then(function () {
               console.log('Joined group Group1');
           })
           .catch(function (err) {
               console.error('Error joining group', err);
           });
   })
   .catch(function (err) {
       console.error('Error during connection: ', err);
   });
    在服务器上调用
  • AddToGroup
    方法将 Excel 加载项添加到指定组(“Group1”)。然后,当消息发送到组时,该组中的客户端将收到该消息。

  • 在浏览器开发者工具中检查控制台日志,以确保连接成功并且您正在加入群组。

  • 从后台发送消息到群组。收到的消息应记录在浏览器控制台中。

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.