Exemplo n.º 1
0
        /// <summary>
        ///     Connect to the server and start processing messages
        /// </summary>
        public void Connect()
        {
            _webSocket?.Dispose();

            _disconnectCalled = false;

            // get the connection info from the signalr host
            var connInf = SignalR.Negotiate(_httpHost, _hubs);

            // we only work with websockets
            if (!connInf.TryWebSockets)
            {
                throw new WebSocketException(WebSocketError.UnsupportedProtocol,
                                             "WebSocket Connections Not Supported By This Host");
            }

            _connectionToken = connInf.ConnectionToken;
            _connectionId    = connInf.ConnectionId;

            _webSocket = SignalR.Connect(_wsHost, _connectionToken, _hubs);

            HookupEvents();

            _webSocket.Connect();

            if (Debug)
            {
                WriteLine($"Connect Called, URL: {_rootHost}");
            }
        }
Exemplo n.º 2
0
        public async Task <bool> Connect()
        {
            try
            {
                _webSocket.OnStateChanged += _webSocket_OnStateChanged;
                _webSocket.OnMessage      += _webSocket_OnMessage;
                _webSocket.OnClosed       += _webSocket_OnClosed;
                _webSocket.OnSendFailed   += _webSocket_OnSendFailed;
                _webSocket.OnData         += _webSocket_OnData;

                try
                {
                    _loxData = await webApi.GetBasicAuthRequest <LoxApp3Data>("/data/LoxAPP3.json");
                }
                catch
                {
                    return(false);
                }
                _keepAliveTimer.Start();
                var connect = _webSocket.Connect();

                if (connect)
                {
                    await InitConnection();
                }
                return(connect);
            }
            catch (Exception e)
            {
                throw;
            }
        }
Exemplo n.º 3
0
        public static void Main(string[] args)
        {
            _timer = new Timer(OnTick, null, 2000, 1);

RESTART:
            var socketOptions = new PureWebSocketOptions()
            {
                DebugMode           = true,
                SendDelay           = 100,
                IgnoreCertErrors    = true,
                MyReconnectStrategy = new ReconnectStrategy(2000, 4000, 20)
            };

            _ws = new PureWebSocket("wss://echo.websocket.org", socketOptions);

            _ws.OnStateChanged += Ws_OnStateChanged;
            _ws.OnMessage      += Ws_OnMessage;
            _ws.OnClosed       += Ws_OnClosed;
            _ws.OnSendFailed   += Ws_OnSendFailed;
            _ws.Connect();

            Console.ReadLine();
            _ws.Dispose(true);
            goto RESTART;
        }
Exemplo n.º 4
0
        /// <summary>
        /// State used while trying to connect.
        /// </summary>
        private void Connecting()
        {
            Log.Information("State::Connecting.");

            Receive <Socket_Connected>(msg => Become(Subscribed));
            Receive <Socket_Disconnected>(msg => Become(Disconnected));

            Log.Information("Starting connection to {0}.", _url);

            // start connecting
            _socket = new PureWebSocket(
                _url,
                new PureWebSocketOptions
            {
                SendDelay = 100,
                DebugMode = false
            });

            _socket.OnStateChanged += Socket_OnStateChanged(Self);
            _socket.OnMessage      += Socket_OnMessage(_subscriber);
            _socket.OnClosed       += Socket_OnClosed(Self);

            try
            {
                _socket.Connect();
            }
            catch
            {
                // socket close handler will be called
            }
        }
Exemplo n.º 5
0
        public void Connect()
        {
            if (IsConnected())
            {
                return;
            }

            Disconnect(() =>
            {
                var opts = new PureWebSocketOptions
                {
                    MyReconnectStrategy = new ReconnectStrategy(1000, 30000)
                };
                _conn            = new PureWebSocket(_endPoint, opts);
                _conn.OnOpened  += OnConnOpen;
                _conn.OnError   += OnConnError;
                _conn.OnMessage += OnConnMessage;
                _conn.OnClosed  += OnConnClose;
                try
                {
                    _conn.Connect();
                    _reconnectTimer.Stop();
                }
                catch (Exception ex)
                {
                    _reconnectTimer.Start();
                }
            });
        }
Exemplo n.º 6
0
        internal bool Connect()
        {
            _websocket             = new PureWebSocket(_url, _purePusherClient.Options);
            _websocket.OnOpened   += _websocket_OnOpened;
            _websocket.OnError    += _websocket_OnError;
            _websocket.OnClosed   += _websocket_OnClosed;
            _websocket.OnFatality += _websocket_OnFatality;
            _websocket.OnMessage  += _websocket_OnMessage;

            return(_websocket.Connect());
        }
Exemplo n.º 7
0
        public void Connect(string url)
        {
            ws = new PureWebSocket(url, new ReconnectStrategy(10000, 60000));

            ws.OnMessage      += OnMessage;
            ws.OnSendFailed   += OnSendFailed;
            ws.OnError        += OnError;
            ws.OnClosed       += OnClosed;
            ws.OnStateChanged += OnStateChanged;
            ws.OnOpened       += Ws_OnOpened;

            ws.Connect();
        }
Exemplo n.º 8
0
 public bool Connect()
 {
     Log("Connect invoked.");
     try
     {
         return(_socket.Connect());
     }
     catch (Exception ex)
     {
         Log($"Connect thew an exception, {ex.Message}.");
         Socket_OnError(this, ex);
         throw;
     }
 }
Exemplo n.º 9
0
        internal async Task <JsonZKill.Killmail> GetSocketResponce()
        {
            try
            {
                if (_webSocket == null || _webSocket.State != WebSocketState.Open)
                {
                    if (_webSocket?.State == WebSocketState.Connecting)
                    {
                        return(null);
                    }
                    var o = new PureWebSocketOptions();
                    _webSocket?.Dispose();
                    _webSocket            = new PureWebSocket(SettingsManager.Settings.Config.ZKillboardWebSocketUrl, o);
                    _webSocket.OnMessage += _webSocket_OnMessage;
                    _webSocket.OnError   += async exception => { await LogHelper.LogEx("_webSocket.OnError", exception, LogCat.ZKill); };

                    if (!_webSocket.Connect())
                    {
                        _webSocket?.Dispose();
                        _webSocket = null;
                        return(null);
                    }
                    else
                    {
                        if (!_webSocket.Send("{\"action\":\"sub\",\"channel\":\"killstream\"}"))
                        {
                            _webSocket?.Dispose();
                            _webSocket = null;
                            return(null);
                        }

                        await LogHelper.LogInfo("ZKB feed core WebSocket connect successful!", LogCat.ZKill);
                    }
                }

                if (!_webMailsQueue.IsEmpty && _webMailsQueue.TryDequeue(out var km))
                {
                    return(km);
                }
            }
            catch (Exception ex)
            {
                await LogHelper.LogEx("GetSocketResponce", ex, LogCat.ZKill);

                _webSocket?.Dispose();
                _webSocket = null;
            }

            return(null);
        }
        /// <summary>
        /// Connects to a UserData Websocket endpoint.
        /// </summary>
        /// <param name="parameters">Paremeters to send to the Websocket.</param>
        /// <param name="accountHandler">Deletage to callback after receive a account info message.</param>
        /// <param name="tradeHandler">Deletage to callback after receive a trade message.</param>
        /// <param name="orderHandler">Deletage to callback after receive a order message.</param>
        public void ConnectToUserDataWebSocket(string parameters, MessageHandler <AccountUpdatedMessage> accountHandler, MessageHandler <OrderOrTradeUpdatedMessage> tradeHandler, MessageHandler <OrderOrTradeUpdatedMessage> orderHandler)
        {
            var finalEndpoint = _webSocketEndpoint + parameters;

            var ws = new PureWebSocket(finalEndpoint, new PureWebSocketOptions()
            {
                DebugMode           = false,//true,
                SendDelay           = 10,
                IgnoreCertErrors    = true,
                MyReconnectStrategy = new ReconnectStrategy(2000, 4000, 20)
            });

            ws.OnMessage += (data) =>
            {
                var eventData = JsonConvert.DeserializeObject <dynamic>(data);

                switch (eventData.e)
                {
                case "outboundAccountInfo":
                    accountHandler(JsonConvert.DeserializeObject <AccountUpdatedMessage>(data));
                    break;

                case "executionReport":
                    var isTrade = ((string)eventData.x).ToLower() == "trade";

                    if (isTrade)
                    {
                        tradeHandler(JsonConvert.DeserializeObject <OrderOrTradeUpdatedMessage>(data));
                    }
                    else
                    {
                        orderHandler(JsonConvert.DeserializeObject <OrderOrTradeUpdatedMessage>(data));
                    }
                    break;
                }
            };

            ws.OnClosed += (reason) =>
            {
                _openSockets.Remove(ws);
            };

            ws.OnError += (error) =>
            {
                _openSockets.Remove(ws);
            };

            ws.Connect();
            _openSockets.Add(ws);
        }
Exemplo n.º 11
0
        public static void Main(string[] args)
        {
            _timer = new Timer(OnTick, null, 2000, 1);

RESTART:
            _ws                 = new PureWebSocket("wss://echo.websocket.org", new ReconnectStrategy(10000, 60000));
            _ws.SendDelay       = 100;
            _ws.OnStateChanged += Ws_OnStateChanged;
            _ws.OnMessage      += Ws_OnMessage;
            _ws.OnClosed       += Ws_OnClosed;
            _ws.OnSendFailed   += Ws_OnSendFailed;
            _ws.Connect();

            Console.ReadLine();
            _ws.Dispose(true);
            goto RESTART;
        }
Exemplo n.º 12
0
        protected override async Task GetExchangeDataAsync(CancellationToken ct)
        {
            var options = new PureWebSocketOptions
            {
                DebugMode = false
            };

            using (var ws = new PureWebSocket(TickerUrl, options))
            {
                var closed = false;

                ws.OnMessage += WsOnMessage;
                ws.OnClosed  += reason =>
                {
                    Logger.Info($"Binance closed: {reason}");
                    closed = true;
                };
                ws.OnError += exception =>
                {
                    Logger.Error(exception);
                    closed = true;
                };

                if (!ws.Connect( ))
                {
                    Logger.Error("Couldn't connect to Binance");
                }

                while (ws.State != WebSocketState.Closed)
                {
                    if (UpTime > LastUpdateDuration &&
                        LastUpdateDuration > TimeSpan.FromHours(1) ||
                        closed)
                    {
                        ws.Disconnect( );
                        break;
                    }

                    await Task.Delay(PollingRate, ct).ConfigureAwait(false);
                }
            }
        }
        /// <summary>
        /// Connects to a Websocket endpoint.
        /// </summary>
        /// <typeparam name="T">Type used to parsed the response message.</typeparam>
        /// <param name="parameters">Paremeters to send to the Websocket.</param>
        /// <param name="messageDelegate">Deletage to callback after receive a message.</param>
        /// <param name="useCustomParser">Specifies if needs to use a custom parser for the response message.</param>
        public void ConnectToWebSocket <T>(string parameters, MessageHandler <T> messageHandler, bool useCustomParser = false)
        {
            var finalEndpoint = _webSocketEndpoint + parameters;

            var ws = new PureWebSocket(finalEndpoint, new PureWebSocketOptions()
            {
                DebugMode           = false,//true,
                SendDelay           = 10,
                IgnoreCertErrors    = true,
                MyReconnectStrategy = new ReconnectStrategy(2000, 4000, 20)
            });

            ws.OnMessage += (data) =>
            {
                dynamic eventData;

                if (useCustomParser)
                {
                    var customParser = new CustomParser();
                    eventData = customParser.GetParsedDepthMessage(JsonConvert.DeserializeObject <dynamic>(data));
                }
                else
                {
                    eventData = JsonConvert.DeserializeObject <T>(data);
                }

                messageHandler(eventData);
            };

            ws.OnClosed += (reason) =>
            {
                _openSockets.Remove(ws);
            };

            ws.OnError += (error) =>
            {
                _openSockets.Remove(ws);
            };

            ws.Connect();
            _openSockets.Add(ws);
        }
Exemplo n.º 14
0
        private void ConnectionMonitorCheck(object state)
        {
            if (_disposedValue || _disconnectCalled)
            {
                return;
            }
            if (_lastMessageTime.AddSeconds(30) > DateTime.Now)
            {
                return;
            }

            if (Debug)
            {
                WriteLine("Connection Timeout, Atempting Reconnect");
            }

            _webSocket.Dispose(false);
            _webSocket = SignalR.Reconnect(_wsHost, _connectionToken, _hubs, _lastMessageId, _groupsToken);

            HookupEvents();

            _webSocket.Connect();
        }
Exemplo n.º 15
0
        protected override void DoOpen()
        {
            Logger.Log("DoOpen uri =" + Uri());

            var myheaders = new List <Tuple <string, string> >();

            myheaders.AddRange(_myExtraHeaders);
            myheaders.Add(new Tuple <string, string>("Cookie", _cookies));

            var options = new PureWebSocketOptions
            {
                Headers = myheaders
            };

            Ws = new PureWebSocket(Uri(), options);

            Ws.OnOpened  += Ws_OnOpened;
            Ws.OnClosed  += Ws_OnClosed;
            Ws.OnData    += Ws_OnData;
            Ws.OnMessage += Ws_OnMessage;
            Ws.OnError   += Ws_OnError;

            Ws.Connect();
        }
Exemplo n.º 16
0
 private void SocketClosed(WebSocketCloseStatus reason)
 {
     _logger.Warning("Socket closed. Reason: {Reason}", reason);
     _webSocket.Connect();
 }
Exemplo n.º 17
0
 public void Connect()
 {
     webSocket.Connect();
     Debug.WriteLine($"[WS] Connecting to {WebSocketUrl}...");
 }