Пример #1
0
        /// <summary>
        /// Handler for a socket closing. Reconnects the socket if needed, or removes it from the active socket list if not
        /// </summary>
        /// <param name="socket">The socket that was closed</param>
        protected virtual void SocketOnClose(IWebsocket socket)
        {
            if (socket.ShouldReconnect)
            {
                if (socket.Reconnecting)
                {
                    return; // Already reconnecting
                }
                socket.Reconnecting = true;

                log.Write(LogVerbosity.Info, $"Socket {socket.Id} Connection lost, will try to reconnect");
                Task.Run(() =>
                {
                    Thread.Sleep(ReconnectInterval);
                    socket.Reset();

                    if (!socket.Connect().Result)
                    {
                        log.Write(LogVerbosity.Debug, $"Socket {socket.Id} failed to reconnect");
                        return; // Connect() should result in a SocketClosed event so we end up here again
                    }
                    var time = socket.DisconnectTime;
                    socket.DisconnectTime = null;
                    if (time == null)
                    {
                        return;
                    }

                    log.Write(LogVerbosity.Info, $"Socket {socket.Id} reconnected after {DateTime.UtcNow - time}");

                    SocketSubscription subscription;
                    lock (sockets)
                        subscription = sockets.Single(s => s.Socket == socket);

                    socket.Reconnecting = false;
                    if (!SocketReconnect(subscription, DateTime.UtcNow - time.Value))
                    {
                        socket.Close().Wait(); // Close so we end up reconnecting again
                    }
                    else
                    {
                        log.Write(LogVerbosity.Info, $"Socket {socket.Id} successfully resubscribed");
                    }
                });
            }
            else
            {
                log.Write(LogVerbosity.Info, $"Socket {socket.Id} closed");
                socket.Dispose();
                lock (sockets)
                {
                    var subscription = sockets.SingleOrDefault(s => s.Socket.Id == socket.Id);
                    if (subscription != null)
                    {
                        sockets.Remove(subscription);
                    }
                }
            }
        }