将消息广播到几个netcore客户端应用程序的最佳方法是什么?

时间:2019-04-17 21:17:30

标签: tcp websocket .net-core asp.net-core-webapi .net-standard

我需要将json消息同时发送到一千个dotnet核心应用程序到同一网络中。目前,我将Rest Web API与自托管的Kestrel服务器一起使用,我问我这是否是最佳解决方案。是否存在用于dotnet核心应用程序或其他解决方案的自托管消息代理?

2 个答案:

答案 0 :(得分:1)

您可以将Service Bus与Topic一起使用。您可以将消息发送到一个主题,并向该主题订阅N个应用程序以接收消息。

每个应用程序都可以在主题下拥有自己的订阅。查找有关如何创建主题和订阅的更多信息here

您可以使用Service Bus Explorer进行本地调试并查看消息。

答案 1 :(得分:0)

我会选择signalR

定义您的中心

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

namespace SignalRChat.Hubs
{
    public class ChatHub : Hub
    {
       public async Task SendMessage(string user, string message)
       {
          await Clients.All.SendAsync("ReceiveMessage", user, message);
       }
    }
}

StartUp中添加SignalR

 services.AddSignalR();

 app.UseSignalR(routes =>
 {
      routes.MapHub<ChatHub>("/chatHub");
 });     

然后定义客户端(不要忘记包含js库signalr.js

"use strict";

var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();

//Disable send button until connection is established
document.getElementById("sendButton").disabled = true;

connection.on("ReceiveMessage", function (user, message) {
    var msg = message.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
    var encodedMsg = user + " says " + msg;
    var li = document.createElement("li");
    li.textContent = encodedMsg;
    document.getElementById("messagesList").appendChild(li);
});

connection.start().then(function(){
    document.getElementById("sendButton").disabled = false;
}).catch(function (err) {
    return console.error(err.toString());
});

document.getElementById("sendButton").addEventListener("click", function (event) {
    var user = document.getElementById("userInput").value;
    var message = document.getElementById("messageInput").value;
    connection.invoke("SendMessage", user, message).catch(function (err) {
        return console.error(err.toString());
    });
    event.preventDefault();
});

SendMessage在Hub中定义为方法,服务器将监听它。 ReceiveMessage是客户端上的侦听器,用于显示服务器发送的内容。

来自 signalR documentation

的所有代码