gpt4 book ai didi

asp.net-core - AspNetCore.SignalR SendAsync 未在 OnConnectedAsync 内部触发

转载 作者:行者123 更新时间:2023-12-05 04:02:37 25 4
gpt4 key购买 nike

我遇到了一个问题,我想在有人连接到集线器时向前端发送一个事件,但前端没有收到通知。我想我可能对直接从集线器调用方法与使用 IHubContext 调用方法感到困惑。我找不到与这些版本相关的太多信息,因此非常感谢您的帮助!

包版本:

Server side (.Net Core 2.2): Microsoft.AspNetCore.SignalR (1.1.0)
Client side (React): @aspnet/signalr:1.1.0

所以这是我的示例中心:

public class MyHub: Hub<IMyHub>
{
public override async Task OnConnectedAsync()
{
// This newMessage call is what is not being received on the front end
await Clients.All.SendAsync("newMessage", "test");

// This console.WriteLine does print when I bring up the component in the front end.
Console.WriteLine("Test");

await base.OnConnectedAsync();
}

public Task SendNewMessage(string message)
{
return Clients.All.SendAsync("newMessage", message);
}
}

现在,我目前的工作调用是在一个服务中,但它正在像这样发送“newMessage”:

public class MessageService: IMessageService
{
private readonly IHubContext<MyHub> _myHubContext;

public MessageService(IHubContext<MyHub> myHubContext)
{
_myHubContext = myHubContext;
}

public async Task SendMessage(string message)
{
// I noticed tis calls SendAsync from the hub context,
// instead of the SendMessage method on the hub, so maybe
// the onConnectedAsync needs to be called from the context somehow also?
await _myHubContext.Clients.All.SendAsync("newMessage", message);
}
}

所以上面的服务方法调用有效并且会联系前端,这是我在 react 组件中的前端连接的例子:

const signalR = require('@aspnet/signalr');

class MessageComponent extends React.Component {
connection: any = null;

componentDidMount() {
this.connection = new signalR.HubConnectionBuilder()
.withUrl('http://localhost:9900/myHub')
.build();

this.connection.on('newMessage', (message: string) => {
// This works when called from the service IHubContext
// but not OnConncectedAsync in MyHub
console.log(message);
});

this.connection.start();
}

componentWillUnmount() {
this.connection.stop();
}

render() {
...
}
}

最佳答案

这是因为您使用的是强类型集线器 (https://learn.microsoft.com/en-us/aspnet/core/signalr/hubs?view=aspnetcore-2.2#strongly-typed-hubs)。

我假设您在 IMyHub 接口(interface)上定义了 SendAsync,因此服务器使用 method = SendAsync, arguments = "newMessage", "test “。如果您删除了 IMyHub 类型,那么这将按预期工作。

关于asp.net-core - AspNetCore.SignalR SendAsync 未在 OnConnectedAsync 内部触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54332558/

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