Ядро SignalR - Попытка передать clientId в Hub, не может понять, как получить - PullRequest
1 голос
/ 06 ноября 2019

Просто нужно передать clientId в мой запрос через концентратор, но я не смог найти подходящий пример того, как передать и получить параметр. Я попытался добавить clientId в ProductCountEventReceiverService, но затем Хаб перестал отвечать.

Мой код

public interface IEventHub
{
    Task ProductCountSendNoticeEventToClient(string message, string clientId);
}
public class EventHub : Hub<IEventHub>
{
    // method for client to invoke
}
public class ProductCountEventReceiverService
{
    private readonly IHubContext<EventHub> _eventHub;

    private Timer _EventGenTimer;

    public ProductCountEventReceiverService(IHubContext<EventHub> eventHub,  string clientId)
    {
        _eventHub = eventHub;

        Init();
    }

    private void Init()
    {
        _EventGenTimer = new Timer(5 * 1000)
        {
            AutoReset = false
        };

        _EventGenTimer.Elapsed += EventGenTimer_Elapsed;
    }

    public void StartReceive()
    {
        _EventGenTimer.Start();
    }

    private void EventGenTimer_Elapsed(object sender, ElapsedEventArgs e)
    {
        _EventGenTimer.Enabled = false;

        var counts = Business.Product.GetCounts("837");  //Get the ClientID here

        _eventHub.Clients.All.SendAsync(nameof(IEventHub.ProductCountSendNoticeEventToClient),
            JsonConvert.SerializeObject(counts)).GetAwaiter().GetResult();

        _EventGenTimer.Enabled = true;
    }
}

Мой запуск // SignalR ниже, добавив бла-бла, потому чтопереполнение стека не позволяет мне представить, что очень раздражает бла-бла-бла-бла-бла-бла-бла-бла-бла-бла-бла-бла

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSignalR();
        services.AddSingleton<ProductCountEventReceiverService>();
    }

   public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        app.UseSignalR(routes =>
        {
            routes.MapHub<EventHub>("/eventHub");
        });
     }

Мой Javascript

var connection = new signalR.HubConnectionBuilder()
    .withUrl("/eventHub?clientId=837")
    .build();

Object.defineProperty(WebSocket, 'OPEN', { value: 1 });
var clientId = $("#CurrentClientId").val();

connection.on("ProductCountSendNoticeEventToClient", clientId, function (message) {

    var result = $.parseJSON(message);
    //Do something here
});

connection.start().catch(function (err) {
    return console.error(err.toString());
});

1 Ответ

0 голосов
/ 07 ноября 2019

Для отправки сообщения с сервера на клиент

 public async Task SendMessage(string user, string message)
 {
   await Clients.All.SendAsync("ReceiveMessage", user, message);
 }

Для получения сообщения от клиента используйте connection.on

connection.on("ReceiveMessage", function (user, message) { }

Для отправки сообщения с клиента на сервер используйте connection.invoke

connection.invoke("SendMessage", user, message).catch(function (err) {
        return console.error(err.toString());
    });

Вы можете просмотреть здесь

...