【发布时间】:2019-01-23 17:24:21
【问题描述】:
我有一个问题,我想在有人连接到集线器时向前端发送一个事件,但前端没有收到通知。我想我可能对直接从集线器调用方法与使用 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() {
...
}
}
【问题讨论】:
-
我怀疑
base.OnConnectedAsync应该被称为 beforeClients.All.SendAsync;它可能是将新客户端添加到Clients.All的基本实现。
标签: asp.net-core signalr asp.net-core-2.0 signalr.client asp.net-core-signalr