public async Task SendMessageBeforeStart_ShouldWorkAfterStart()
        {
            var url = new Uri("wss://www.bitmex.com/realtime");

            using (var client = new WebsocketClient(url))
            {
                string received      = null;
                var    receivedCount = 0;
                var    receivedEvent = new ManualResetEvent(false);

                await client.Send("ping");

                await client.Send("ping");

                await client.Send("ping");

                await client.Send("ping");

                client
                .MessageReceived
                .Where(x => x.ToLower().Contains("pong"))
                .Subscribe(msg =>
                {
                    receivedCount++;
                    received = msg;

                    if (receivedCount >= 7)
                    {
                        receivedEvent.Set();
                    }
                });

                await client.Start();

                await client.Send("ping");

                await client.Send("ping");

                await client.Send("ping");

                receivedEvent.WaitOne(TimeSpan.FromSeconds(30));

                Assert.NotNull(received);
            }
        }
Example #2
0
        static IWebsocketClient Connect()
        {
            var url = new Uri("ws://127.0.0.1/");

            using var client = new WebsocketClient(url)
                  {
                      ReconnectTimeout = TimeSpan.FromSeconds(30)
                  };

            client.ReconnectionHappened.Subscribe(info =>
                                                  Console.WriteLine($"Reconnection happened, type: {info.Type}"));

            client.MessageReceived.Subscribe(msg => Console.WriteLine($"Message received: {msg}"));

            client.Start();

            return(client);
        }
Example #3
0
        public Client(Settings settings)
        {
            Settings = settings;

            client = new WebsocketClient(Settings.GetNextUri());

            client.ReconnectTimeout      = null;
            client.ErrorReconnectTimeout = TimeSpan.FromSeconds(1);
            client.DisconnectionHappened.Subscribe(info =>
            {
                client.Url = Settings.GetNextUri();
                Settings.InvokeDisconnected(this, info);
            });
            client.ReconnectionHappened.Subscribe(info => { Settings.InvokeReconnected(this, info); });

            client.MessageReceived.Subscribe(msg => { Settings.InvokeMessageReceived(this, msg); });
            client.Start();
        }
Example #4
0
        public async Task Start()
        {
            var exitEvent = new ManualResetEvent(false);

            using (var client = new WebsocketClient(_url))
            {
                client.ReconnectTimeout = TimeSpan.FromSeconds(30);

                client.MessageReceived.Subscribe(msg => {
                    Console.Write($"\rMessage Received: {msg}        ");
                    SaveMessage(msg);
                });

                await client.Start();

                exitEvent.WaitOne();
            }
        }
Example #5
0
        static void Main(string[] args)
        {
            var exitEvent = new ManualResetEvent(false);
            var url       = new Uri("ws://localhost:5000/ws");

            using (var client = new WebsocketClient(url))
            {
                client.ReconnectTimeout = TimeSpan.FromSeconds(30);
                client.ReconnectionHappened.Subscribe(info =>
                                                      Console.WriteLine($"Reconnection happened, type: {info.Type}"));

                client.MessageReceived.Subscribe(msg => Console.WriteLine($"Message received: {msg}"));
                client.Start();

                Task.Run(() => client.Send("test echo 123"));

                exitEvent.WaitOne();
            }
        }
Example #6
0
        /// <summary>
        /// 获取Clash连接WebSocket
        /// </summary>
        public void GetClashConnection()
        {
            CloseClashConnection();

            var socket = new WebsocketClient(new Uri(API_CONNECTIONS_WS + GetToken()));

            socket.Start();
            ConnectionWebSocketClient = socket;
            ConnectionWebSocketClient.MessageReceived.ObserveOn(TaskPoolScheduler.Default).Subscribe(msg =>
            {
                if (ConnectionUpdatedEvt != null)
                {
                    var response = JsonConvert.DeserializeObject <ClashConnectionResponse>(msg.Text);
                    ConnectionUpdatedEvt.Invoke(null, new ConnectionEvtArgs {
                        Response = response
                    });
                }
            });
        }
        public static void Connect()
        {
            if (client != null && client.IsRunning)
            {
                client.Stop(System.Net.WebSockets.WebSocketCloseStatus.NormalClosure, "");
            }

            success = false;
            client  = new WebsocketClient(new Uri(NexusMods.SSODomain));
            client.ReconnectTimeout = ReconnectTimeout;
            client.ReconnectionHappened.Subscribe(OnReconnect);
            client.MessageReceived.Subscribe(OnMessage);
            client.DisconnectionHappened.Subscribe(OnDisconnect);
            client.Start();

            string data = BuildLoginData();

            client.Send(data); // SendInstant
        }
        static void Main(string[] args)
        {
            InitLogging();

            AppDomain.CurrentDomain.ProcessExit += CurrentDomainOnProcessExit;
            Console.CancelKeyPress += ConsoleOnCancelKeyPress;

            Console.WriteLine("|=======================|");
            Console.WriteLine("|    WEBSOCKET CLIENT   |");
            Console.WriteLine("|=======================|");
            Console.WriteLine();

            Log.Debug("====================================");
            Log.Debug("              STARTING              ");
            Log.Debug("====================================");



            var url = new Uri("wss://www.bitmex.com/realtime");

            using (var client = new WebsocketClient(url))
            {
                client.Name = "Bitmex";
                client.ReconnectTimeoutMs = (int)TimeSpan.FromSeconds(30).TotalMilliseconds;
                client.ReconnectionHappened.Subscribe(type =>
                                                      Log.Information($"Reconnection happened, type: {type}"));
                client.DisconnectionHappened.Subscribe(type =>
                                                       Log.Warning($"Disconnection happened, type: {type}"));

                client.MessageReceived.Subscribe(msg => Log.Information($"Message received: {msg}"));

                client.Start();

                Task.Run(() => StartSendingPing(client));

                ExitEvent.WaitOne();
            }

            Log.Debug("====================================");
            Log.Debug("              STOPPING              ");
            Log.Debug("====================================");
            Log.CloseAndFlush();
        }
Example #9
0
        /// <summary>
        /// 获取Clash日志WebSocket
        /// </summary>
        public void GetClashLog()
        {
            CloseClashLog();

            var socket = new WebsocketClient(new Uri(API_LOGS + GetToken()));

            socket.Start();
            LoggingWebSocketClient = socket;
            LoggingWebSocketClient.MessageReceived.ObserveOn(TaskPoolScheduler.Default).Subscribe(msg =>
            {
                if (LoggingReceivedEvt != null)
                {
                    var response = JsonConvert.DeserializeObject <ClashLogResponse>(msg.Text);
                    LoggingReceivedEvt.Invoke(null, new LoggingEvtArgs {
                        Response = response
                    });
                }
            });
        }
Example #10
0
        public async Task MonitorEvents(string websocketAddress)
        {
            if (_exitEvent != null)
            {
                _botLogger.LogDanger("Bot is trying to establish a new connection while there is already a connection.");
                return;
            }
            _exitEvent = new ManualResetEvent(false);

            // Start websocket.
            var url    = new Uri(websocketAddress);
            var client = new WebsocketClient(url)
            {
                ReconnectTimeout = TimeSpan.FromDays(1)
            };

            client.ReconnectionHappened.Subscribe(type => _botLogger.LogVerbose($"WebSocket: {type.Type}"));
            var subscription = client.DisconnectionHappened.Subscribe((t) =>
            {
                _botLogger.LogDanger("Websocket connection dropped!");
                _exitEvent?.Set();
                _exitEvent = null;
            });
            await client.Start();

            // log.
            _botLogger.LogInfo("Listening to your account channel.");
            _botLogger.LogVerbose(websocketAddress + "\n");
            _botLogger.AppendResult(true, 9);

            // Post connect event.
            await _eventSyncer.Init(client);

            await BuildBot.OnBotStarted();

            // Pend.
            _exitEvent?.WaitOne();
            subscription.Dispose();
            await client.Stop(WebSocketCloseStatus.NormalClosure, string.Empty);

            _botLogger.LogVerbose("Websocket connection disconnected.");
        }
        static void Main(string[] args)
        {
            var exitEvent = new ManualResetEvent(false);
            IConfigurationRoot configuration = new ConfigurationBuilder()
                                               .SetBasePath(Directory.GetCurrentDirectory())
                                               .AddJsonFile("Config.json")
                                               .Build();
            var setting = new Settings();

            configuration.Bind(setting);

            Currencies.checkSymbolsForAvailabilityInExchanges(setting);
            Currencies.formedPairs();

            List <Symbol> symbols = Utils.InitSymbols(setting);

            List <SymbolMarket> symbolMarkets = Utils.InitSymbolMarkets(setting, symbols, client);

            string        gateioJson = Utils.gateioStringGenerator(symbols);
            string        okexJson   = Utils.okexStringGenerator(symbols);
            List <string> huobuJsons = Utils.huobiStringGenerator(symbols);

            WebsocketClient gateioClient = WebSocketClients.StartGateIO(setting.Urls.gateio, symbols, symbolMarkets);

            Task.Run(() => gateioClient.Start());
            Task.Run(() => gateioClient.Send($"{gateioJson}"));

            WebsocketClient okexClient = WebSocketClients.StartOkex(setting.Urls.okex, symbols, symbolMarkets);

            Task.Run(() => okexClient.Start());
            Task.Run(() => okexClient.Send($"{okexJson}"));

            WebsocketClient huobiClient = WebSocketClients.StartHuobi(setting.Urls.huobi, symbols, symbolMarkets);

            Task.Run(() => huobiClient.Start());
            foreach (string hubiJson in huobuJsons)
            {
                Task.Run(() => huobiClient.Send($"{hubiJson}"));
            }

            exitEvent.WaitOne();
        }
Example #12
0
        public async Task OnStarting_ShouldGetInfoResponse()
        {
            using (IWebsocketClient client = new WebsocketClient(WebsocketUrl))
            {
                string received      = null;
                var    receivedEvent = new ManualResetEvent(false);

                client.MessageReceived.Subscribe(msg =>
                {
                    received = msg.Text;
                    receivedEvent.Set();
                });

                await client.Start();

                receivedEvent.WaitOne(TimeSpan.FromSeconds(30));

                Assert.NotNull(received);
            }
        }
Example #13
0
        public async Task Connect(string webSocketUrl)
        {
            if (_client != null)
            {
                await Close();
            }

            var uri = new Uri(webSocketUrl);

            _client = new WebsocketClient(uri)
            {
                ReconnectTimeout      = _reconnectTimeout,
                IsReconnectionEnabled = true
            };

            _client.MessageReceived.Subscribe(MessageReceived);
            _client.DisconnectionHappened.Subscribe(Disconnected);

            await _client.Start();
        }
Example #14
0
        protected async Task ConnectBaseAsync()
        {
            if (WsClient == null)
            {
                await _wsLock.WaitAsync().ConfigureAwait(false);

                if (WsClient == null)
                {
                    InitWsClient();
                }

                _wsLock.Release();
            }

            await WsClient.Start().ConfigureAwait(false);

            await EnsureConnectedOnStartAsync().ConfigureAwait(false);

            _pingCts = new CancellationTokenSource();
            _        = HeartbeatsAsync(_pingCts.Token);
        }
        public async Task OnStarting_ShouldGetInfoResponse()
        {
            var url = new Uri("wss://www.bitmex.com/realtime");

            using (var client = new WebsocketClient(url))
            {
                string received      = null;
                var    receivedEvent = new ManualResetEvent(false);

                client.MessageReceived.Subscribe(msg =>
                {
                    received = msg.Text;
                    receivedEvent.Set();
                });

                await client.Start();

                receivedEvent.WaitOne(TimeSpan.FromSeconds(30));

                Assert.NotNull(received);
            }
        }
        public StocksManager(IDependenciesManager _dependencies)
        {
            stocksValues = new List <StockValue>();
            Task.Run(() =>
            {
                using (var client = new WebsocketClient(new Uri(_dependencies.stocksendpoint)))
                {
                    client.ReconnectTimeout = TimeSpan.FromSeconds(30);
                    //client.ReconnectionHappened.Subscribe(info =>
                    //    Log.Information($"Reconnection happened, type: {info.Type}"));

                    client.MessageReceived.Subscribe(msg =>
                    {
                        try
                        {
                            var value        = JsonConvert.DeserializeObject <Dictionary <string, double> >(msg.ToString());
                            StockValue stock = stocksValues.FirstOrDefault(s => s.StockCode.Equals(value.Keys.ElementAt(0))) ?? new StockValue {
                                StockCode = value.Keys.ElementAt(0)
                            };
                            if (stock.Timestamp < value["timestamp"])
                            {
                                stock.Value     = value[stock.StockCode];
                                stock.Timestamp = value["timestamp"];
                                if (!stocksValues.Any(s => s.StockCode.Equals(value.Keys.ElementAt(0))))
                                {
                                    stocksValues.Add(stock);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                    });
                    client.Start();
                    new ManualResetEvent(false).WaitOne();
                }
            });
        }
        private async void OpenDataEvents()
        {
            string prefix = SecureConnection ? "wss" : "ws";
            var    uri    = new Uri($"{prefix}://{HostName}/events/marketdata/");

            DataSocket = new WebsocketClient(uri, GetWSFactory());
            DataSocket.ReconnectTimeout      = null;
            DataSocket.IsReconnectionEnabled = true;
            DataSocket.ReconnectionHappened.Subscribe(info => {
                logger.Warn($"Reconnection happened, reason: {info.Type}, stream: data");
                System.Diagnostics.Debug.WriteLine($"Reconnection happened, type: {info.Type}, stream: data");
                DataReconnected?.Invoke();
            });
            DataSocket.DisconnectionHappened.Subscribe(info => {
                logger.Warn($"Disconnection happened, reason: {info.Type}, stream: data");
                DataDisconnected?.Invoke();
            });
            DataSocket.MessageReceived.Subscribe(msg =>
                                                 MessageReceived?.Invoke(msg.Binary));
            await DataSocket.Start();

            DataConnected?.Invoke();
        }
Example #18
0
        public void LoriotWebsocketStart()
        {
            Func <ClientWebSocket> factory = new Func <ClientWebSocket>(() =>
            {
                var clientWebSocket = new ClientWebSocket
                {
                    Options =
                    {
                        KeepAliveInterval = TimeSpan.FromSeconds(60)
                    }
                };
                return(clientWebSocket);
            });

            clientWS = new WebsocketClient(uri, factory);

            clientWS.ReconnectTimeout      = null;
            clientWS.ErrorReconnectTimeout = TimeSpan.FromSeconds(60);

            setupMessageRecieve(clientWS);
            clientWS.Start();
            Console.WriteLine("Loriot Running.\n");
        }
Example #19
0
        public async void Connect()
        {
            GetSettings();
            try
            {
                var exitEvent = new ManualResetEvent(false);
                var url       = new Uri($"ws://{ip}:{port.ToString()}");

                this.client = new WebsocketClient(url);

                this.client.ReconnectTimeout = null;
                this.client.ReconnectionHappened.Subscribe(info =>
                                                           Console.WriteLine($"Reconnection happened, type: {info.Type}"));

                this.client.MessageEncoding = Encoding.Default;
                await client.Start();
            }
            catch (Exception e)
            {
                MessageBox.Show("Произошла фатальная ошибка.\nПерезапустите программу или обратитесь к администратору.", "FATAL", MessageBoxButton.OK, MessageBoxImage.Error);
                Globals.Logger.Error("FATAL: " + e.ToString());
            }
        }
Example #20
0
        /// <summary>
        /// Enables websocket client channel
        /// </summary>
        /// <param name="ReconnectTimeout">Time range in ms, how long to wait before reconnecting if no message comes from the server</param>
        public Task EnableWebSocketConnection(int ReconnectTimeout = 30)
        {
            var url = new Uri(GetUri("/websocket").Replace("https://", "ws://"));

            // configure client web socket options
            var factory = new Func <ClientWebSocket>(() => new ClientWebSocket
            {
                Options = { KeepAliveInterval = TimeSpan.FromSeconds(10) }
            });

            ws?.Dispose();
            ws = new WebsocketClient(url, factory);

            ws.ReconnectTimeout = TimeSpan.FromSeconds(30);

            ws.ReconnectionHappened.Subscribe(info =>
            {
                WebSocketAuthChallenge auth = new WebSocketAuthChallenge(settings.Token);
                ws.Send(JsonSerializer.Serialize(auth));
            });

            return(ws.Start());
        }
Example #21
0
    static async Task Main(string[] args)
    {
        HttpClient client = new HttpClient();

        client.DefaultRequestHeaders.Add("user", UserID);
        dynamic response  = JsonConvert.DeserializeObject(await client.GetStringAsync(LoginEndpoint));
        string  sessionId = response.sessionId;

        Console.WriteLine("Obtained session ID: " + sessionId);

        using (var socket = new WebsocketClient(WebSocketEndpoint))
        {
            await socket.Start();

            socket.MessageReceived.Subscribe(msg =>
            {
                dynamic payload = JsonConvert.DeserializeObject(msg.Text);
                if (payload["event"] == "sessionInvalidated")
                {
                    Console.WriteLine("You have logged in elsewhere. Exiting.");
                    Environment.Exit(0);
                }
            });

            socket.Send(JsonConvert.SerializeObject(new
            {
                action = "subscribeToSessionInvalidation",
                args   = new
                {
                    sessionId = sessionId
                }
            }));

            Console.WriteLine("Press ENTER to exit.");
            Console.ReadLine();
        }
    }
Example #22
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseMvc();

            app.UseWebSockets();

            var exitEvent = new ManualResetEvent(false);
            var url       = new Uri(ps2ApiEndpoint);

            using (var ws = new WebsocketClient(url))
            {
                ws.ReconnectTimeoutMs = (int)TimeSpan.FromSeconds(30).TotalMilliseconds;
                ws.ReconnectionHappened.Subscribe(type =>
                                                  Debug.WriteLine($"Reconnection happened, type: {type}"));

                ws.MessageReceived.Subscribe(msg => Debug.WriteLine($"Message received: {msg}"));
                ws.Start();

                var    item       = "1125904204410686";
                string sendString =
                    "{\r\n\t\"service\":\"event\",\r\n\t\"action\":\"subscribe\",\r\n\t\"characters\":[" + item + "],\r\n\t\"eventNames\":[\"Deaths\", \"PlayerLogin\", \"PlayerLogout\"]\r\n}";
                Task.Run(() => ws.Send(sendString));

                exitEvent.WaitOne();
            }
        }
        private async Task OpenTradeEvents()
        {
            string prefix = SecureConnection ? "wss" : "ws";
            var    uri    = new Uri($"{prefix}://{HostName}/events/order/");

            OrderSocket = new WebsocketClient(uri, GetWSFactory(true));
            OrderSocket.ReconnectTimeout      = null;
            OrderSocket.IsReconnectionEnabled = true;
            OrderSocket.ReconnectionHappened.Subscribe(info =>
            {
                logger.Warn($"Reconnection happened, reason: {info.Type}, stream: trade");
                System.Diagnostics.Debug.WriteLine($"Reconnection happened, type: {info.Type}, stream: trade");
                if (info.Type != ReconnectionType.Initial)
                {
                    ControlReconnected?.Invoke();
                }
            });
            OrderSocket.DisconnectionHappened.Subscribe(info =>
            {
                logger.Error($"Disconnected, reason: {info.Type}, exception: {info.Exception}");
                System.Diagnostics.Debug.WriteLine($"Disconnected, type: {info.Type}");
                ControlDisconnected?.Invoke();
                if (info.Type == DisconnectionType.ByServer || info.Type == DisconnectionType.NoMessageReceived)
                {
                    Task.Run(async() => await OpenTradeEvents());
                }
                else
                {
                    logger.Fatal($"Disconnected, reason: {info.Type}, exception: {info.Exception}");
                }
            });
            OrderSocket.MessageReceived.Subscribe(msg => MessageReceived?.Invoke(msg.Binary));
            await OrderSocket.Start();

            ControlConnected?.Invoke();
        }
Example #24
0
 public async Task SetupDiscordWebSocket()
 {
     Func<ClientWebSocket> factory = () => new ClientWebSocket()
     {
         Options =
         {
             KeepAliveInterval = TimeSpan.FromSeconds(120),
             Credentials = CredentialCache.DefaultNetworkCredentials,
             UseDefaultCredentials = true
         }
     };
     using (discordWebSocket = new WebsocketClient(new Uri(discordUrl), factory))
     {
         discordWebSocket.IsReconnectionEnabled = true;
         discordWebSocket.ErrorReconnectTimeout = TimeSpan.FromSeconds(30);
         discordWebSocket.ReconnectTimeout = null; //TimeSpan.FromSeconds(60);
         discordWebSocket.MessageReceived.Subscribe(HandleDiscordWebSocketMessage);
         discordWebSocket.ReconnectionHappened.Subscribe(HandleDiscordWebSocketReconnection);
         discordWebSocket.DisconnectionHappened.Subscribe(HandleDiscordWebSocketDisconnection);
         discordWebSocket.Start();
         Console.WriteLine("Started WebSocket Client for Discord bot");
         exitEvent.WaitOne();
     }
 }
 public async Task Connect()
 {
     await client.Start();
 }
Example #26
0
        public async Task Connect()
        {
            if (_socketConnection != null && _socketConnection.IsRunning)
            {
                return;
            }

            var uri = new Uri(_baseUrl);

            _socketConnection = new WebsocketClient(uri);
            _socketConnection.ReconnectTimeout      = TimeSpan.FromSeconds(60);
            _socketConnection.ErrorReconnectTimeout = TimeSpan.FromSeconds(30);
            _socketConnection.ReconnectionHappened.Subscribe(info =>
            {
                if (!_restoreConnection)
                {
                    return;
                }
                Login().Wait();
                RestoreSubscriptions();
            });
            _socketConnection.DisconnectionHappened.Subscribe(info =>
            {
                info.CancelReconnection = !_restoreConnection;
                if (info.Type == DisconnectionType.ByUser ||
                    info.Type == DisconnectionType.Exit ||
                    info.Type == DisconnectionType.NoMessageReceived)
                {
                    return;
                }
                OnError(new UnhandledExceptionEventArgs(info.Exception, false));
            });
            _socketConnection.MessageReceived.Subscribe(msg =>
            {
                switch (msg.MessageType)
                {
                case WebSocketMessageType.Text:
                    try
                    {
                        foreach (var socketAction in _socketActions.Values.ToList())
                        {
                            var result = socketAction.ProcessResponse(msg.Text);

                            if (socketAction is SingleSocketAction singleSocketAction)
                            {
                                if (result)
                                {
                                    singleSocketAction.Complete();
                                }

                                if (singleSocketAction.Completed)
                                {
                                    _socketActions.TryRemove(singleSocketAction.Id, out _);
                                    break;
                                }
                            }
                        }
                    }
                    catch (Exception exception)
                    {
                        OnError(new UnhandledExceptionEventArgs(exception, false));
                    }
                    break;
                }
            });

            await _socketConnection.Start();
        }
Example #27
0
        /// <summary>
        /// Start streaming
        /// </summary>
        /// <returns></returns>
        public override async Task Subscribe()
        {
            await Unsubscribe();

            // Orders

            var orderSubscription = OrderSenderStream.Subscribe(message =>
            {
                switch (message.Action)
                {
                case ActionEnum.Create: CreateOrders(message.Next); break;

                case ActionEnum.Update: UpdateOrders(message.Next); break;

                case ActionEnum.Delete: DeleteOrders(message.Next); break;
                }
            });

            _subscriptions.Add(orderSubscription);

            // Streaming

            _streamSession = await GetStreamSession();

            var client = new WebsocketClient(new Uri(StreamSource + "/markets/events"), _streamOptions)
            {
                Name                  = Account.Name,
                ReconnectTimeout      = TimeSpan.FromSeconds(30),
                ErrorReconnectTimeout = TimeSpan.FromSeconds(30)
            };

            var connectionSubscription    = client.ReconnectionHappened.Subscribe(message => { });
            var disconnectionSubscription = client.DisconnectionHappened.Subscribe(message => { });
            var messageSubscription       = client.MessageReceived.Subscribe(message =>
            {
                dynamic input = JObject.Parse(message.Text);

                switch ($"{ input.type }")
                {
                case "quote":

                    OnInputQuote(ConversionManager.Deserialize <InputPointModel>(message.Text));
                    break;

                case "trade": break;

                case "tradex": break;

                case "summary": break;

                case "timesale": break;
                }
            });

            _subscriptions.Add(messageSubscription);
            _subscriptions.Add(connectionSubscription);
            _subscriptions.Add(disconnectionSubscription);
            _subscriptions.Add(client);

            await client.Start();

            var query = new
            {
                linebreak       = true,
                advancedDetails = true,
                sessionid       = _streamSession,
                symbols         = Account.Instruments.Values.Select(o => o.Name)
            };

            client.Send(ConversionManager.Serialize(query));
        }
Example #28
0
 public void Start()
 {
     ws = new WebsocketClient(new Uri($"wss://stream.pushbullet.com/websocket/{apiKey}"));
     ws.MessageReceived.Subscribe(OnWebSocketMessage);
     ws.Start();
 }
Example #29
0
        public static async Task WsConnect(BotData data, string url, int keepAliveMilliseconds = 5000)
        {
            data.Logger.LogHeader();

            IWebProxy proxy = null;

            if (data.UseProxy)
            {
                if (data.Proxy.Type != Models.Proxies.ProxyType.Http)
                {
                    throw new NotSupportedException("Only http proxies are supported");
                }
                else
                {
                    proxy = new WebProxy(data.Proxy.Host, data.Proxy.Port);

                    if (data.Proxy.NeedsAuthentication)
                    {
                        proxy.Credentials = new NetworkCredential(data.Proxy.Username, data.Proxy.Password);
                    }
                }
            }

            var factory = new Func <ClientWebSocket>(() => new ClientWebSocket
            {
                Options =
                {
                    KeepAliveInterval = TimeSpan.FromMilliseconds(keepAliveMilliseconds),
                    Proxy             = proxy
                }
            });

            var wsMessages = new List <string>();

            data.Objects["wsMessages"] = wsMessages;

            var ws = new WebsocketClient(new Uri(url), factory)
            {
                IsReconnectionEnabled = false,
                ErrorReconnectTimeout = null
            };

            ws.MessageReceived.Subscribe(msg =>
            {
                lock (wsMessages)
                {
                    wsMessages.Add(msg.Text);
                }
            });

            // Connect
            await ws.Start();

            if (!ws.IsRunning)
            {
                throw new Exception("Failed to connect to the websocket");
            }

            data.Objects["webSocket"] = ws;

            data.Logger.Log($"The Web Socket client connected to {url}", LogColors.MossGreen);
        }
Example #30
0
        public void ConnectToSocket()
        {
            var exitEvent = new ManualResetEvent(false);
            var url       = new Uri("wss://sso.nexusmods.com");

            using (var client = new WebsocketClient(url))
            {
                client.ReconnectTimeout = TimeSpan.FromSeconds(30);
                //client.ReconnectionHappened.Subscribe(info => Log.Information($"Reconnection happened, type: {info.Type}"));

                client.MessageReceived.Subscribe(msg =>
                {
                    try
                    {
                        System.Diagnostics.Debug.WriteLine($"Message received: {msg}");

                        Response = System.Text.Json.JsonSerializer.Deserialize <NexusResponse>(msg.Text);

                        if (Response.success)
                        {
                            if (!string.IsNullOrEmpty(Response.data.connection_token))
                            {
                                ConnectionToken = Response.data.connection_token;

                                OnGotConnectionToken(new NexusResponseEventArgs
                                {
                                    ConnectionToken = ConnectionToken
                                });
                            }

                            if (!string.IsNullOrEmpty(Response.data.api_key))
                            {
                                ApiKey = Response.data.api_key;

                                OnGotApiKey(new NexusResponseEventArgs
                                {
                                    ApiKey = ApiKey
                                });
                            }

                            //Reset data so there's definitely nothing there (old data) if using Response object later.
                            Response.data = new NexusData();
                        }
                        else
                        {
                            throw new Exception(Response.error.ToString());
                        }
                    }
                    catch (Exception e)
                    {
                        OnException(new NexusExceptionArgs {
                            ex = e
                        });
                    }
                });

                client.MessageReceived.Subscribe(msg =>

                                                 Response = System.Text.Json.JsonSerializer.Deserialize <NexusResponse>(msg.Text)
                                                 );

                client.Start();

                data = new NexusRequestData
                {
                    id       = Uuid,
                    protocol = 2,
                    token    = ConnectionToken
                };

                Task.Run(() =>
                {
                    client.Send(System.Text.Json.JsonSerializer.Serialize(data));
                });

                exitEvent.WaitOne();
            }
        }