SignalR - Send message OnConnected

后端 未结 4 1709
半阙折子戏
半阙折子戏 2021-02-14 02:15

I\'ve been experimenting with SignalR today and It\'s really neat. Basically what I wanted to achieve is the following:

As soon as a device connects it should send a mes

4条回答
  •  没有蜡笔的小新
    2021-02-14 03:12

    Since you haven't established a connection yet, trying to call your client .hello() function within OnConnected is not possible at this point. However, we can define a server hub method and immediately call that upon our connection .done callback. Then, in our new server method we can reallocate the logic you currently have in OnConnected.

    This will change our setup quite a bit and introduce some additional steps, but observe the following example...

    // WhateverHub
    public override Task OnConnected()
    {
        return base.OnConnected()
    }
    
    public void AfterConnected()
    {
        // if(stuff) -- whatever if/else first user/last user logic
        // {
            Clients.Caller.hello("message")
        // }
    }
    

    var proxy= $.connection.whateverHub;
    
    proxy.client.hello = function(message) {
        // last step in event chain
    }
    
    $.connection.hub.start().done(function () {
        proxy.server.afterConnected() // call AfterConnected() on hub
    });
    

    So the basic idea here is to first

    1. Connect => .done(function() { ... });
    2. Call server.afterConnected()
    3. Execute logic within that method
    4. If we're satisfied with conditions call our .hello() client function

    Note - this implementation is for a JavaScript client - but the same idea can be translated to a .net client. This is mostly an architectural issue.

提交回复
热议问题