代码之家  ›  专栏  ›  技术社区  ›  Shawn

aspnetcore.signal sendAsync未在OnConnectedAsync内部激发

  •  0
  • Shawn  · 技术社区  · 7 年前

    我有一个问题,当有人连接到集线器时,我想向前端发送一个事件,但是前端没有收到通知。我想我可能会混淆直接从hub调用方法和使用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() {
            ...
        }
    }
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Brennan    7 年前

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

    我想你定义了 SendAsync 对你 IMyHub 接口,因此服务器发送消息时 method = SendAsync, arguments = "newMessage", "test" . 如果你把你的 IMYHUB 然后键入,它将按预期工作。

    推荐文章