First arbitrary messages in signalR has no message

2019-03-02 06:29发布

问题:

I wrote this simple code which --when connected , should yield

  • "FIRST !"
  • "Welcome"
  • 3 messages ( timer)

This is the code :

int i = 0;
protected override Task OnConnected(IRequest request, string connectionId)
{

    //first message
    Connection.Send(connectionId, "FIRST !"); //first message

    //last messages
    Timer _timer = new Timer(RunMe, new    {con = connectionId, req = request}, 2000, 1000);    

    //second message
    return Connection.Send(connectionId, "Welcome!"); //second message


}

void RunMe(dynamic state)
{
    if (i < 3)
    {
        Connection.Send((string) state.con, "Loop " + i);
        i++;
    }
}

and here the JS code ( inside document.ready block) :

...

connection.received(function (data)
        {

        $('#messages').append('<li><b>data received = </b>' + data +
                                  "<b>ConnectionId =</b> " + connection.id + 
                                  '<b>MessageId = </b>' + connection.messageId + '</li>');
    });

I do get all responses.

But if I press f5(refresh) -- these are the typical responses :

Refresh again ,

It seems that the first message never gets a messageID :

And later messages sometimes get messageID and sometimes not.

ps

I thought to myself , maybe it's an initialization speed problems , so I tried this :

And again , the response was :

  • What's going on here ? why the first messages doesn't get messageID ? how can I fix that ?

回答1:

In SignalR 1.1, connection.messageId is set after all of the connection.received handlers have been called for a batch of messages.

Message IDs are really only meant to be used by SignalR internally, but in SignalR 2.0 connection.messageId will be set before the connection.received handlers are called.