Exemple #1
0
        private void OnConnected()
        {
            IsConnected = true;
#if DEBUG
            Console.WriteLine("[+++] Map connection opened");
#endif
            ConnectionOpened?.Invoke();
        }
Exemple #2
0
        private void _socket_Opened(object sender, EventArgs e)
        {
            SetAuthentication();
            SubscribeSystemTopics();
            SubscribeSymbolTopics();

            ConnectionOpened?.Invoke(this, e);
        }
Exemple #3
0
 public MessageHandler(IChannel channel, MessageReceived <T> onMessage, ConnectionClosed <T> onConnectionClosed,
                       ConnectionOpened <T> onConnectionOpened)
 {
     this.Channel            = channel;
     this.OnMessage          = onMessage;
     this.OnConnectionClosed = onConnectionClosed;
     this.OnConnectionOpened = onConnectionOpened;
 }
Exemple #4
0
        public void StartClient()
        {
            socket         = new WebSocket(wsURI);
            socket.Opened += (x, y) => ConnectionOpened?.Invoke();
            socket.Open();
            socket.MessageReceived += InvokeMessageReceived;

            socket.Error += (sender, args) => NewErrorMessage?.Invoke(args.Exception.Message);
        }
Exemple #5
0
 void WebSocketOpened(object sender, EventArgs e)
 {
     connectionOpenEvent.Set();             // send signal about connection done
     if (!ConnectionOpened.IsNull())
     {
         ConnectionOpened(this);
     }
     receivedQueue.Enqueue(Response.Open(Url));
 }
        private void OnWebSocketConnected()
        {
            DebugLogger.Log("[SnipeClient] OnWebSocketConnected");

            try
            {
                ConnectionOpened?.Invoke();
            }
            catch (Exception e)
            {
                DebugLogger.Log("[SnipeClient] OnWebSocketConnected - ConnectionOpened invokation error: " + e.Message);
            }
        }
Exemple #7
0
        public static void Open(string port, int rate)
        {
            if (port == null)
            {
                throw new ArgumentNullException(nameof(port));
            }

            if (!AvailableBitRates.Contains(rate))
            {
                throw new ArgumentOutOfRangeException(nameof(rate));
            }

            if (IsOpen)
            {
                return;
            }

            s_SerialPort = new SerialPort(port, rate, Parity.None, 8, StopBits.One)
            {
                WriteTimeout = 1000,
                DtrEnable    = false
            };

            try
            {
                s_SerialPort.Open();
            }
            catch (UnauthorizedAccessException e)
            {
                throw new UCComException(StringRes.StringRes.UCComUnauthorizedAccess, e);
            }
            catch (IOException e)
            {
                throw new UCComException(StringRes.StringRes.UCComIOError, e);
            }

            IsOpen = true;

            kickoffRead();

            ConnectionOpened?.Invoke(null, EventArgs.Empty);

            // This was done by Program.cs and AdvancedPage.cs
            byte[] ret = SendCommand(1, 0, 0);

            if (ret == null || ret.Length != 1 || ret[0] != Constants.SUPPORTED_EEPROM_VERSION)
            {
                Close();
                throw new UCComException(StringRes.StringRes.UCComBadVersion);
            }
        }
        private static void GetDatabase()
        {
            lock (dbSync)
            {
                database = GetFromServer <SneezeDatabase>(Messages.DatabaseRequested, Messages.DatabaseObject);
                ConnectionOpened?.Invoke();
                if (!VerifyDatabase())
                {
                    return;
                }
            }

            GotDatabase?.Invoke();
        }
 private void HandleConnectionOpened(ConnectionOpened message)
 {
     var jsonPayload = JsonConvert.SerializeObject(new
     {
         Type = "ClientInfo",
         Payload = new Dictionary<string, object>
         {
             ["$$MachineName"] = Environment.MachineName,
             ["$$Username"] = Environment.UserName,
             ["$$ApplicationName"] = _applicationName
         }
     });
     _socket.Send(jsonPayload);
     Context.ActorOf(Props.Create(() => new HearbeatTransmitter(_socket, _heartBeatInterval, _onSendingHearbeat)), "heartbeats");
     Context.Parent.Tell(message);
 }
        private void HandleConnectionOpened(ConnectionOpened message)
        {
            var jsonPayload = JsonConvert.SerializeObject(new
            {
                Type    = "ClientInfo",
                Payload = new Dictionary <string, object>
                {
                    ["$$MachineName"]     = Environment.MachineName,
                    ["$$Username"]        = Environment.UserName,
                    ["$$ApplicationName"] = _applicationName
                }
            });

            _socket.Send(jsonPayload);
            Context.ActorOf(Props.Create(() => new HearbeatTransmitter(_socket, _heartBeatInterval, _onSendingHearbeat)), "heartbeats");
            Context.Parent.Tell(message);
        }
Exemple #11
0
 private void Listen()
 {
     ReceiveAsync <GetConnection>(async g =>
     {
         try
         {
             ConnectionOpened connection = null;
             _randomKey       = SignSafeMod(Random.Next(), _maxConnectionsPerHosts);
             _logicalEndpoint = g.LogicalEndPoint;
             if (g.LogicalEndPoint != null && g.PhusicalEndPoint == null)
             {
                 connection = await GetConnection(g.LogicalEndPoint, _randomKey);
             }
             else if (g.LogicalEndPoint != null && g.PhusicalEndPoint != null)
             {
                 connection = await GetConnection(g.LogicalEndPoint, g.PhusicalEndPoint, _randomKey);
             }
             else
             {
                 connection = await GetConnection(g.LogicalEndPoint, _randomKey);
             }
             Sender.Tell(new AskResponse(connection));
         }
         catch (Exception e)
         {
             Sender.Tell(new AskResponse(PulsarClientException.Unwrap(e)));
         }
     });
     Receive <CleanupConnection>(c =>
     {
         CleanupConnection(c.Address, c.ConnectionKey);
     });
     Receive <CloseAllConnections>(_ =>
     {
         CloseAllConnections();
     });
     Receive <ReleaseConnection>(c =>
     {
         ReleaseConnection(c.ClientCnx);
     });
     Receive <GetPoolSize>(c =>
     {
         Sender.Tell(new GetPoolSizeResponse(PoolSize));
     });
     Stash?.UnstashAll();
 }
        public void Close()
        {
            if (_Session != Guid.Empty)
            {
                lock (_ObjectLock)
                    try
                    {
                        if (_Session != Guid.Empty)
                        {
                            _ConnectCaller = null;

                            _Session = Guid.Empty;

                            try
                            {
                                if (_Socket != null)
                                {
                                    _Socket.Close();
                                }
                            }
                            catch { }

                            try
                            {
                                if (_Socket != null)
                                {
                                    _Socket.Dispose();
                                }
                            }
                            catch { }

                            _ConnectionOpened = null;

                            _Socket = null;

                            _SocketQueue.Clear();

                            if (_ServerClosed != null)
                            {
                                _ServerClosed(this);
                            }
                        }
                    }
                    catch { }
            }
        }
Exemple #13
0
        public static void StartClient()
        {
            string protocol = ConfigurationManager.AppSettings["protocol"];

            switch (protocol)
            {
            case "ws":
                string uri = ConfigurationManager.AppSettings["wsuri"];
                ConnectionClient = new WSClient(uri);
                break;

            default: break;
            }
            ConnectionClient.NewErrorMessage  += (x) => NewErrorMessage?.Invoke(x);
            ConnectionClient.responseReceived += (x) => responseReceived?.Invoke(x);

            ConnectionClient.ConnectionOpened += () => ConnectionOpened?.Invoke();
            ConnectionClient.StartClient();
        }
        void _CallOut()
        {
            try
            {
                while (true)
                {
                    if (_CalloutThread != System.Threading.Thread.CurrentThread)
                    {
                        return;
                    }

                    object cb = null;
                    if (_CallOutQueue.Count > 0)
                    {
                        lock (_CallOutQueue)
                            if (_CallOutQueue.Count > 0)
                            {
                                if (_CalloutThread == System.Threading.Thread.CurrentThread)
                                {
                                    cb = _CallOutQueue.Dequeue();
                                }
                            }
                    }

                    if (cb == null)
                    {
                        lock (_CallOutQueue)
                            if (_CallOutQueue.Count == 0)
                            {
                                if (_CalloutThread == System.Threading.Thread.CurrentThread)
                                {
                                    System.Threading.Monitor.Wait(_CallOutQueue, 250);

                                    if (_CallOutQueue.Count == 0)
                                    {
                                        if (_CalloutThread == System.Threading.Thread.CurrentThread)
                                        {
                                            _CalloutThread = null;
                                            return;
                                        }
                                    }

                                    continue;
                                }
                                else
                                {
                                    return;
                                }
                            }
                    }

                    if (cb != null)
                    {
                        if (cb is ConnectionClosed)
                        {
                            ConnectionClosed c = cb as ConnectionClosed;

                            try
                            {
                                c(this);
                            }
                            catch (Exception ex)
                            {
                                STEM.Sys.EventLog.WriteEntry("Connection.ConnectionClosed", ex.ToString(), STEM.Sys.EventLog.EventLogEntryType.Error);
                            }
                        }
                        else if (cb is ConnectionOpened)
                        {
                            ConnectionOpened c = cb as ConnectionOpened;
                            try
                            {
                                c(this);
                            }
                            catch (Exception ex)
                            {
                                STEM.Sys.EventLog.WriteEntry("Connection.ConnectionOpened", ex.ToString(), STEM.Sys.EventLog.EventLogEntryType.Error);
                            }
                        }

                        cb = null;
                    }
                }
            }
            finally
            {
                lock (_CallOutQueue)
                    if (_CalloutThread == System.Threading.Thread.CurrentThread)
                    {
                        _CalloutThread = null;
                    }
            }
        }
Exemple #15
0
 public sealed override void OnOpen()
 {
     ConnectionOpened?.Invoke(this, EventArgs.Empty);
 }
Exemple #16
0
 private void OnConnectionOpened(DbConnection connection)
 {
     ConnectionOpened?.Invoke(connection, EventArgs.Empty);
 }
Exemple #17
0
 private void Client_ConnectionOpened()
 {
     ConnectionOpened?.Invoke();
     Game.SendAuthentication(Account.Name, Account.Password);
 }
        void Bind(ConnectionOpened callback = null)
        {
            lock (_AccessMutex)
            {
                if (ConnectionRole == TCP.Role.Server)
                {
                    if (_Receiver != null && IsConnected())
                    {
                        if (callback != null)
                        {
                            EnqueueCallout(callback);
                        }

                        return;
                    }

                    if (!IsConnected())
                    {
                        throw new IOException("Client is no longer connected to this server.");
                    }
                }
                else
                {
                    if (!IsConnected())
                    {
                        try
                        {
                            _TcpClient = null;

                            string address = STEM.Sys.IO.Net.MachineAddress(RemoteAddress);

                            if (address == null || System.Net.IPAddress.None.ToString() == address)
                            {
                                throw new Exception("Address could not be reached.");
                            }

                            TcpClient client = new TcpClient(AddressFamily.InterNetwork);
                            client.Connect(RemoteAddress, RemotePort);

                            _TcpClient = client;

                            if (_SslConnection)
                            {
                                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                                _SslStream = new SslStream(_TcpClient.GetStream(), true, new RemoteCertificateValidationCallback(ValidateCertificate), null, EncryptionPolicy.RequireEncryption);

                                _SslStream.ReadTimeout  = 5000;
                                _SslStream.WriteTimeout = 5000;

                                if (_ClientCertificate != null)
                                {
                                    X509CertificateCollection certCollection = new X509CertificateCollection();
                                    certCollection.Add(_ClientCertificate);
                                    _SslStream.AuthenticateAsClient("STEM.Surge", certCollection, System.Security.Authentication.SslProtocols.Tls12, false);
                                }
                                else
                                {
                                    _SslStream.AuthenticateAsClient("STEM.Surge");
                                }
                            }

                            if (!IsConnected())
                            {
                                throw new IOException();
                            }
                        }
                        catch
                        {
                            if (_TcpClient != null)
                            {
                                try
                                {
                                    _TcpClient.Client.Shutdown(SocketShutdown.Both);
                                }
                                catch { }

                                try
                                {
                                    _TcpClient.Close();
                                }
                                catch { }

                                try
                                {
                                    _TcpClient.Dispose();
                                }
                                catch { }
                            }

                            _TcpClient = null;
                            _SslStream = null;
                            return;
                        }
                    }
                    else
                    {
                        if (callback != null)
                        {
                            EnqueueCallout(callback);
                        }

                        return;
                    }
                }

                if (_TcpClient != null)
                {
                    _TcpClient.ReceiveBufferSize   = 1024 * 1024 * 256;
                    _TcpClient.SendBufferSize      = 1024 * 256;
                    _TcpClient.Client.DontFragment = true;
                    _TcpClient.Client.Ttl          = 42;

                    _TcpClient.LingerState = new LingerOption(true, 0);
                    _TcpClient.NoDelay     = true;

                    _TcpClient.ReceiveTimeout = 5000;
                    _TcpClient.SendTimeout    = 5000;

                    RemoteAddress = ((System.Net.IPEndPoint)_TcpClient.Client.RemoteEndPoint).Address.ToString();


                    if (RemoteAddress == STEM.Sys.IO.Net.EmptyAddress)
                    {
                        throw new Exception("Attempt to connect to the EmptyAddress");
                    }

                    RemotePort   = ((System.Net.IPEndPoint)_TcpClient.Client.RemoteEndPoint).Port;
                    LocalAddress = ((System.Net.IPEndPoint)_TcpClient.Client.LocalEndPoint).Address.ToString();
                    LocalPort    = ((System.Net.IPEndPoint)_TcpClient.Client.LocalEndPoint).Port;

                    if (_Receiver == null)
                    {
                        _Receiver = new Thread(new ThreadStart(Receive));
                        _Receiver.IsBackground = true;
                        _Receiver.Priority     = ThreadPriority.Highest;
                        _Receiver.Start();
                    }

                    lock (_CallOutQueue)
                    {
                        if (_ConnectionOpened != null)
                        {
                            foreach (ConnectionOpened c in _ConnectionOpened.GetInvocationList())
                            {
                                EnqueueCallout(c);
                            }
                        }

                        EnqueueCallout(new ConnectionOpened(_Opened));
                    }

                    _CloseBroadcast = false;
                }
            }
        }
Exemple #19
0
 private void Client_ConnectionOpened()
 {
     ConnectionOpened?.Invoke();
     _authenticationRequired = true;
 }
Exemple #20
0
 private void Client_ConnectionOpened()
 {
     ConnectionOpened?.Invoke();
     Game.SendAuthentication(Account.Name, Account.Password, HardwareHash.GenerateRandom());
 }
Exemple #21
0
        void _CallOut()
        {
            while (true)
            {
                try
                {
                    object[] cb = null;
                    lock (_CallOutQueue)
                        if (_CalloutThread == System.Threading.Thread.CurrentThread)
                        {
                            if (_CallOutQueue.Count > 0)
                            {
                                cb = _CallOutQueue.Dequeue();
                            }
                            else
                            {
                                System.Threading.Monitor.Wait(_CallOutQueue, 30000);

                                if (_CallOutQueue.Count == 0)
                                {
                                    if (_CalloutThread == System.Threading.Thread.CurrentThread)
                                    {
                                        _CalloutThread = null;
                                        return;
                                    }
                                }
                            }
                        }
                        else
                        {
                            return;
                        }

                    if (cb != null)
                    {
                        if (cb[0] is ConnectionClosed)
                        {
                            ConnectionClosed c = cb[0] as ConnectionClosed;

                            try
                            {
                                c(this);
                            }
                            catch (Exception ex)
                            {
                                STEM.Sys.EventLog.WriteEntry("Connection.ConnectionClosed", ex.ToString(), STEM.Sys.EventLog.EventLogEntryType.Error);
                            }
                        }
                        else if (cb[0] is ConnectionOpened)
                        {
                            ConnectionOpened c = cb[0] as ConnectionOpened;
                            try
                            {
                                c(this);
                            }
                            catch (Exception ex)
                            {
                                STEM.Sys.EventLog.WriteEntry("Connection.ConnectionOpened", ex.ToString(), STEM.Sys.EventLog.EventLogEntryType.Error);
                            }
                        }
                        else if (cb[0] is ConnectionReceive)
                        {
                            ConnectionReceive c = cb[0] as ConnectionReceive;
                            try
                            {
                                c((byte[])cb[1], (int)cb[2], (DateTime)cb[3]);
                            }
                            catch (Exception ex)
                            {
                                STEM.Sys.EventLog.WriteEntry("Connection.ConnectionReceive", ex.ToString(), STEM.Sys.EventLog.EventLogEntryType.Error);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    STEM.Sys.EventLog.WriteEntry("Connection._CallOut", ex.ToString(), STEM.Sys.EventLog.EventLogEntryType.Error);
                }
            }
        }
 private void WebSocketOpened(object sender, EventArgs e)
 {
     connectionOpenEvent.Set(); // send signal about connection done
     ConnectionOpened.SafeInvoke(this);
     receivedQueue.Enqueue(Response.Open(Url));
 }
 private void OnConnectionOpened()
 {
     ConnectionOpened?.Invoke(this, EventArgs.Empty);
 }
Exemple #24
0
        public static void Open(string port, int rate)
        {
            Logging.WriteBannerToLog("Open");

            if (port == null)
            {
                throw new ArgumentNullException(nameof(port));
            }

            if (!AvailableBitRates.Contains(rate))
            {
                throw new ArgumentOutOfRangeException(nameof(rate));
            }

            if (IsOpen)
            {
                return;
            }

            Logging.WriteLineToLog("Create serial port. Port={0}, Rate={1}", port, rate);
            s_SerialPort = new SerialPort(port, rate, Parity.None, 8, StopBits.One)
            {
                WriteTimeout = 1000,
                ReadTimeout  = 1000,
                DtrEnable    = false // DTR resets Arduino
            };

            Logging.WriteLineToLog("Open the port now.");
            try
            {
                s_SerialPort.Open();
            }
            catch (UnauthorizedAccessException e)
            {
                Logging.WriteLineToLog("Exception from serial port: {0}", e);
                throw new UCComException(StringRes.StringRes.UCComUnauthorizedAccess, e);
            }
            catch (IOException e)
            {
                Logging.WriteLineToLog("Exception from serial port: {0}", e);
                throw new UCComException(StringRes.StringRes.UCComIOError, e);
            }

            Logging.WriteLineToLog("Compatibility check now.");
            byte[] ret;
            try
            {
                ret = SendCommandInternal(1, 0, 0);

                if (ret == null || ret.Length != 1 || ret[0] != Constants.SUPPORTED_EEPROM_VERSION)
                {
                    throw new UCComException(StringRes.StringRes.UCComBadVersion);
                }
            }
            catch (UCComException)
            {
                CloseInternal();
                throw;
            }

            Logging.WriteLineToLog("Serial port is open.");
            IsOpen = true;

            ConnectionOpened?.Invoke(null, EventArgs.Empty);
        }
Exemple #25
0
 private void OnConnected()
 {
     IsConnected = true;
     ConnectionOpened?.Invoke();
     Login();
 }
Exemple #26
0
        public async Task SubscribeAsync(bool reConnectOnDisconnect)
        {
            var uri = ExchangeClientBase.IsSandbox ? WSS_SANDBOX_ENDPOINT_URL : WSS_ENDPOINT_URL;

            if (_authContainer != null)             // authenticated feed
            {
                uri = new Uri(uri, "/users/self/verify");
            }
            cancellationTokenSource = new CancellationTokenSource();

            while (!cancellationTokenSource.IsCancellationRequested)
            {
                string disconnectReason = "";
                try
                {
                    webSocketClient = new ClientWebSocket();
                    await webSocketClient.ConnectAsync(uri, cancellationTokenSource.Token);

                    if (webSocketClient.State == System.Net.WebSockets.WebSocketState.Open && !cancellationTokenSource.IsCancellationRequested)
                    {
                        await rateGateRealtime.WaitToProceedAsync();                         // don't subscribe at too high of a rate
                        await sendSubscriptionMsgAsync(Products : Products, gdax_Channel : gdax_Channel);

                        // key is product name, value is whether connection was just opened
                        if (webSocketClient.State == System.Net.WebSockets.WebSocketState.Open && !cancellationTokenSource.IsCancellationRequested)
                        {                         // checking again bc maybe the server disconnected after the subscribe msg was sent
                                                  // + move to processing subscriptions section below later
                            foreach (var product in Products)
                            {
                                ConnectionOpened?.Invoke(product, gdax_Channel);
                            }
                        }
                        while (webSocketClient.State == System.Net.WebSockets.WebSocketState.Open && !cancellationTokenSource.IsCancellationRequested)
                        {
                            using (var timeoutCTS = new CancellationTokenSource(6500))                             // heartbeat every 1000 ms, so give it 5 hearbeat chances
                                using (var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(timeoutCTS.Token, cancellationTokenSource.Token))
                                    using (var stream = new MemoryStream(1024))
                                    {
                                        var  receiveBuffer = new ArraySegment <byte>(new byte[1024 * 8]);
                                        bool timedOut      = false;
                                        WebSocketReceiveResult webSocketReceiveResult;
                                        do
                                        {
                                            try
                                            {
                                                webSocketReceiveResult = await webSocketClient.ReceiveAsync(receiveBuffer, linkedTokenSource.Token);
                                            }
                                            catch (OperationCanceledException)
                                            {
                                                timedOut         = true;
                                                disconnectReason = " - stream timed out";
                                                break;
                                            }
                                            await stream.WriteAsync(receiveBuffer.Array, receiveBuffer.Offset, webSocketReceiveResult.Count, cancellationTokenSource.Token);
                                        } while (!webSocketReceiveResult.EndOfMessage && !cancellationTokenSource.IsCancellationRequested);

                                        if (!timedOut && !cancellationTokenSource.IsCancellationRequested)
                                        {
                                            var message       = stream.ToArray().Where(b => b != 0).ToArray();
                                            var messageString = Encoding.ASCII.GetString(message, 0, message.Length);
                                            if (!String.IsNullOrEmpty(messageString))
                                            {
                                                try
                                                {
                                                    var jToken = JToken.Parse(messageString);

                                                    var typeToken = jToken["type"];
                                                    if (typeToken == null)
                                                    {
                                                        RealtimeDataError?.Invoke(this, new RealtimeError("null typeToken: + " + Encoding.ASCII.GetString(message, 0, message.Length)));
                                                        return;                                         // go to next msg
                                                    }

                                                    var type = typeToken.Value <string>();
                                                    switch (type)
                                                    {
                                                    case "subscriptions":
                                                        // + process initial subscription confirmation
                                                        // + also for unsubscribe confirmation
                                                        break;

                                                    case "received":
                                                        var rr = new RealtimeReceived(jToken);
                                                        if (rr.Message != null)
                                                        {
                                                            RealtimeDataError?.Invoke(this, rr);
                                                        }
                                                        RealtimeReceived?.Invoke(this, rr);
                                                        break;

                                                    case "open":
                                                        var ro = new RealtimeOpen(jToken);
                                                        if (ro.Message != null)
                                                        {
                                                            RealtimeDataError?.Invoke(this, ro);
                                                        }
                                                        RealtimeOpen?.Invoke(this, ro);
                                                        break;

                                                    case "done":
                                                        var rd = new RealtimeDone(jToken);
                                                        if (rd.Message != null)
                                                        {
                                                            RealtimeDataError?.Invoke(this, rd);
                                                        }
                                                        RealtimeDone?.Invoke(this, rd);
                                                        break;

                                                    case "match":
                                                        var rm = new RealtimeMatch(jToken);
                                                        if (rm.Message != null)
                                                        {
                                                            RealtimeDataError?.Invoke(this, rm);
                                                        }
                                                        RealtimeMatch?.Invoke(this, rm);
                                                        break;

                                                    case "last_match":
                                                        var rlm = new RealtimeMatch(jToken);
                                                        if (rlm.Message != null)
                                                        {
                                                            RealtimeDataError?.Invoke(this, rlm);
                                                        }
                                                        RealtimeLastMatch?.Invoke(this, rlm);
                                                        break;

                                                    case "change":
                                                        var rc = new RealtimeChange(jToken);
                                                        if (rc.Message != null)
                                                        {
                                                            RealtimeDataError?.Invoke(this, rc);
                                                        }
                                                        RealtimeChange?.Invoke(this, rc);
                                                        break;

                                                    case "heartbeat":
                                                        // + should implement this (checking LastTraderId)
                                                        var hb = new Heartbeat(jToken);
                                                        Heartbeat?.Invoke(this, hb);
                                                        break;

                                                    case "error":
                                                        RealtimeDataError?.Invoke(this, new RealtimeError(jToken));
                                                        break;

                                                    default:
                                                        RealtimeDataError?.Invoke(this, new RealtimeError("Unexpected type: " + jToken));
                                                        break;
                                                    }
                                                }
                                                catch (JsonReaderException e)
                                                {
                                                    RealtimeDataError?.Invoke(this, new RealtimeError(
                                                                                  "JsonReaderException: " + e.Message + ":" + messageString));
                                                }
                                            }
                                            else
                                            {
                                                RealtimeDataError?.Invoke(this, new RealtimeError("empty message received. Connection state: "
                                                                                                  + webSocketClient.State + ", linkedToken: " + linkedTokenSource.Token.IsCancellationRequested));
                                            }
                                        }
                                    }
                        }
                    }
                }
                catch (Exception e)
                {
                    if (e.Message == "The remote party closed the WebSocket connection without completing the close handshake.")                     // System.Net.WebSockets.WebSocketException
                    {
                        disconnectReason = " - remote closed the WebSocket w/o completing the close handshake";
                    }
                    else if (e.Message == "Unable to connect to the remote server") // System.Net.WebSockets.WebSocketException
                    {
                        disconnectReason = " - unable to connect to server";        // shorten it a bit
                        await Task.Delay(10000);                                    // if unable to connect, then wait 10 seconds before trying to connect again
                    }
                    else
                    {
                        RealtimeStreamError?.Invoke(this, new RealtimeError("other exception caught: " + e.GetType() + " : " + e.Message));
                    }
                }
                if (!reConnectOnDisconnect)
                {
                    UnSubscribe();
                }
                foreach (var product in Products)
                {
                    RealtimeStreamError?.Invoke(this, new RealtimeError("disconnected" + disconnectReason));
                    ConnectionClosed?.Invoke(product, gdax_Channel);
                }
                if (!reConnectOnDisconnect)
                {
                    break;
                }
            }
        }
Exemple #27
0
 private void OnOpen(object sender, EventArgs e)
 {
     ConnectionOpened?.Invoke(this, EventArgs.Empty);
 }
Exemple #28
0
 private void Client_ConnectionOpened()
 {
     ConnectionOpened?.Invoke();
 }
 internal virtual void OnConnectionOpened(RemotingDbConnection connection)
 {
     ConnectionOpened?.Invoke(connection);
 }