Issue
I have SignalR Hub running on a server being run as a service. This server for whatever reason, may stop due to power loss, being updated (we use Octopus to automatically update), or whatever.
If I have a user connected to this service sending messages to the server, and then in turn, forwarding this message to a sensor. The sensor then returns a message to the server, and gets forwarded on to the client webapp.
This works fine on the first connection. If the service is stopped and restarted before the reconnect times out, I get my reconnect with the same connection id, and I can send messages. I can't however, receive messages.
If I refresh the page, I will get them as this creates a new connection. The same code is called whether it is OnConnect() or OnReconnect().
Example
public override Task OnConnected()
{
EstablishConnection("Connect");
return base.OnConnected();
}
public override Task OnReconnected()
{
// Remove old Connection Id to receive messages on reconnect
ConnectionsHandler.Instance.RemoveTerminalClient(Context.ConnectionId);
EstablishConnection("Reconnect");
// This block is to tell the user that connection has been reconnected. This message shows on the webapp so connection has been restored.
var hubContext = GlobalHost.ConnectionManager.GetHubContext<TerminalHub>();
var message = TerminalMessageColorer.ColorMessageLime(String.Format("Connection has been re-established!"));
hubContext.Clients.Client(Context.ConnectionId).TerminalEcho(message);
return base.OnReconnected();
}
private void EstablishConnection(string conType)
{
ConnectionsHandler.Instance.AddTerminalClient(Context.ConnectionId, "null");
var terminal = ConnectionsHandler.Instance.GetTerminalClient(Context.ConnectionId);
#if DEBUG
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("{0}\t{1}\t...{2}", terminal, Context.ConnectionId, conType);
#endif
}
Solution
I found what the problem was. I needed to wrap a $timeout in the client side code as there seems to be a little delay in the C# code. I stumbled across this from the chrome dev tools once I was debugging the initializer, thinking something had to be wrong that the user id wasn't being passed. Once I added a breakpoint at the call to initialize, it would go there so that work, but continuing from there I would receive messages afterwards. Without the breakpoint I wouldn't. So I added the $timeout around the call.
$timeout(function () {
initializeTerminal();
}, 100);
Answered By - Tomaltach
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.