gpt4 book ai didi

javascript - SignalR 核心 - 尝试将 clientId 传递给 Hub,无法弄清楚如何接收

转载 作者:太空宇宙 更新时间:2023-11-04 01:22:35 25 4
gpt4 key购买 nike

只需通过集线器将 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;
}
}

我的创业//下面的信号R添加等等,因为堆栈溢出不会让我提交,这非常烦人哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈

    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());
});

最佳答案

从服务器向客户端发送消息

 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());
});

您可以查看here

关于javascript - SignalR 核心 - 尝试将 clientId 传递给 Hub,无法弄清楚如何接收,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58732077/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com