Exemplo n.º 1
0
 /// <inheritdoc/>
 public override void Dispose()
 {
     base.Dispose();
     disconnectionHappenedSubscription?.Dispose();
     messageReceivedSubscription?.Dispose();
     webSocketClient?.Stop(WebSocketCloseStatus.NormalClosure, "Planned closure of web socket.");
     webSocketClient?.Dispose();
 }
Exemplo n.º 2
0
 public override void Close()
 {
     Log("preparing to close Rhasspy thread, ignore core dumped!");
     exitEvent.Set();
     websocketClient.Dispose();
     listeningThread.Interrupt();
 }
Exemplo n.º 3
0
        /// <summary>
        /// Dispose
        /// </summary>
        /// <returns></returns>
        public async ValueTask DisposeAsync()
        {
            await WebsocketClient.CloseAsync(WebSocketCloseStatus.NormalClosure, "unavailable", CancellationToken.None);

            WebsocketClient.Dispose();
            await OnDisconnectAsync();
        }
Exemplo n.º 4
0
 public void Dispose()
 {
     if (client != null)
     {
         client.Dispose();
     }
 }
Exemplo n.º 5
0
 public void Dispose()
 {
     ApplicationManager.Instance.PlayerEvent     -= HandlePlayerEvent;
     ApplicationManager.Instance.ServerListEvent -= HandleServerListEvent;
     ApplicationManager.Instance.PlayerEvent     -= HandleServerListEvent;
     discordWebSocket?.Dispose();
     exitEvent?.Dispose();
 }
Exemplo n.º 6
0
        public void Dispose()
        {
            _receiveBuffer.Complete();
            _handleMessagesCts.Cancel();

            // TODO: isn't thread safe, could crush on app terminating.
            WsClient?.Dispose();
        }
Exemplo n.º 7
0
        static void Main(string[] args)
        {
            ManualResetEvent ExitEvent = new ManualResetEvent(false);

            Console.WriteLine("Hello World!");
            // basic object parser
            var testOject = new {
                worker = "me"
            };
            var testString = Parser.ToMessage(MessageType.INFO, testOject);

            Console.WriteLine(testString);

            // Exception parser
            var testExceptString = Parser.ToMessage(MessageType.INFO, new Exception("A Exception Occur"));

            // try the real one
            // try {
            //   var testCli = new WSConnecter("ws://127.0.0.1:9002");
            //   testCli.Info("test message in string");
            //   testCli.Info(new { message = "test message in string" });
            //   testCli.Error(new Exception("A Exception Occur"));
            //   testCli.Disconect();
            // } catch (Exception e) {
            //   Console.WriteLine(e);
            // }
            var url = "ws://127.0.0.1:9002";

            try {
                using (var ws_client = new WebsocketClient(new Uri(url))) {
                    ws_client.ReconnectTimeout = TimeSpan.FromSeconds(30);
                    ws_client.Start().Wait();
                    Task.Run(() => {
                        ws_client.Send(
                            Parser.ToMessage(MessageType.INFO, "incomes single msg")
                            );
                        ExitEvent.WaitOne();
                    });
                    Task.Run(() => {
                        ws_client.Send(
                            Parser.ToMessage(MessageType.INFO, testString)
                            );
                        ExitEvent.WaitOne();
                    });
                    Task.Run(() => {
                        ws_client.Send(
                            Parser.ToMessage(MessageType.INFO, testExceptString)
                            );
                        ExitEvent.WaitOne();
                    });
                    ExitEvent.WaitOne();
                    ws_client.Dispose();
                }
                ExitEvent.Dispose();
            } catch (Exception excep) {
                Console.WriteLine(excep);
            }
        }
Exemplo n.º 8
0
        private async Task CheckConfig()
        {
            string    token     = TokenTextBox.Text;
            var       output    = false;
            var       received  = 0;
            Exception exception = null;

            try
            {
                CheckButton.IsEnabled = false;
                SaveButton.IsEnabled  = false;
                WebsocketClient client      = new WebsocketClient(new Uri(GetUrl()));
                var             authMessage = $"{{\"type\": \"auth\",\"access_token\": \"{token}\"}}";
                client.Start();
                client.MessageReceived.Subscribe(msg =>
                {
                    var type = (string)JObject.Parse(msg.Text)["type"];
                    if (type == "auth_required")
                    {
                        client.Send(authMessage);
                        return;
                    }

                    output   = type == "auth_ok";
                    received = -10;
                    client.Stop(WebSocketCloseStatus.NormalClosure, "");
                    client.Dispose();
                });
                client.Send(authMessage);
                while (received < 10 && received >= 0)
                {
                    received++;
                    await Task.Delay(50);
                }
            }
            catch (Exception e)
            {
                exception = e;
            }

            if (exception != null)
            {
                ConsoleWriter.WriteLine($"Error while connecting: {exception.Message}", ConsoleColor.Red);
            }
            else if (!output && received == 10)
            {
                ConsoleWriter.WriteLine("Unable to connect", ConsoleColor.Red);
            }
            else
            {
                ConsoleWriter.WriteLine("Invalid credentials", ConsoleColor.Red);
            }

            SaveButton.IsEnabled    = output;
            UrlTextBox.Background   = output ? _normalColor : InvalidColor;
            TokenTextBox.Background = output ? _normalColor : InvalidColor;
            CheckButton.IsEnabled   = true;
        }
Exemplo n.º 9
0
 public void OnClose(DisconnectionInfo info)
 {
     if (client != null)
     {
         client.Dispose();
     }
     Console.WriteLine("Socket closed");
     Application.Exit();
 }
        public async Task Revoke()
        {
            foreach (var subscription in _subscriptions)
            {
                await subscription.Revoke();
            }

            _subscriptions.Clear();
            _ws.Dispose();
        }
Exemplo n.º 11
0
        private async Task InitialiseWS()
        {
            var url = new Uri("ws://localhost:9010");

            var factory = new Func <ClientWebSocket>(() =>
            {
                var client = new ClientWebSocket();
                client.Options.UseDefaultCredentials = false;
                client.Options.SetRequestHeader("Origin", "file://");
                client.Options.SetRequestHeader("Pragma", "no-cache");
                client.Options.SetRequestHeader("Cache-Control", "no-cache");
                client.Options.SetRequestHeader("Sec-WebSocket-Extensions", "permessage-deflate; client_max_window_bits");
                client.Options.SetRequestHeader("Sec-WebSocket-Protocol", "json");
                client.Options.AddSubProtocol("json");
                return(client);
            });

            _ws?.Dispose();
            _ws = new WebsocketClient(url, factory);
            _ws.MessageReceived.Subscribe(ParseSocketMsg);
            _ws.ErrorReconnectTimeout = TimeSpan.FromMilliseconds(500);
            _ws.ReconnectTimeout      = null;

            Debug.WriteLine($"Trying to connect to LGHUB_agent, at {url}");

            try
            {
                await _ws.StartOrFail();
            }
            catch (Websocket.Client.Exceptions.WebsocketException)
            {
                Debug.WriteLine("Failed to connect to LGHUB_agent");
                _ws?.Dispose();
                _ws = null;
                return;
            }

            Debug.WriteLine($"Connected to LGHUB_agent");

            _ws.Send(JsonConvert.SerializeObject(new
            {
                msgId = "",
                verb  = "SUBSCRIBE",
                path  = "/devices/state/changed"
            }));

            _ws.Send(JsonConvert.SerializeObject(new
            {
                msgId = "",
                verb  = "SUBSCRIBE",
                path  = "/battery/state/changed"
            }));
        }
Exemplo n.º 12
0
 public override void Dispose()
 {
     SetStatus(DisplayStatus.Closing);
     if (websocket != null)
     {
         Console.WriteLine("websocket close requested");
         websocket.IsReconnectionEnabled = false;
         websocket.Stop(WebSocketCloseStatus.NormalClosure, "Stop");
         websocket.Dispose();
         Console.WriteLine("websocket closed");
     }
 }
Exemplo n.º 13
0
        private bool disposedValue = false; // To detect redundant calls

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    _subscription?.Dispose();
                    _socket.Dispose();
                }

                disposedValue = true;
            }
        }
Exemplo n.º 14
0
 public void Dispose()
 {
     SendMessage("Disconnecting UI24R....", false);
     if (_client != null)
     {
         _client.Dispose();
         _client = null;
     }
     if ((_settings.Controller is IDisposable) && _settings.Controller != null)
     {
         (_settings.Controller as IDisposable).Dispose();
     }
 }
        private void Dispose(bool disposing)
        {
            if (!Disposed)
            {
                if (disposing)
                {
                    _reconnectionHandler.Dispose();
                    _client.Dispose();
                }

                Disposed = true;
            }
        }
Exemplo n.º 16
0
        protected virtual void Dispose(bool disposing)
        {
            if (_isDisposed)
            {
                return;
            }

            if (disposing)
            {
                _client.Dispose();
            }

            _isDisposed = true;
        }
 public void Close(bool Abort = false)
 {
     if (_ws.IsRunning)
     {
         if (Abort)
         {
             _ws.Stop(WebSocketCloseStatus.NormalClosure, "Close");
         }
         else
         {
             _ws.Dispose();
         }
     }
 }
 /// <summary>
 /// Dispose method.
 /// </summary>
 public void Dispose()
 {
     DataSocket?.Stop(WebSocketCloseStatus.Empty, "");
     DataSocket?.Dispose();
     DataSocket = null;
     OrderSocket?.Stop(WebSocketCloseStatus.Empty, "");
     OrderSocket?.Dispose();
     OrderSocket         = null;
     DataConnected       = null;
     DataReconnected     = null;
     DataDisconnected    = null;
     ControlConnected    = null;
     ControlReconnected  = null;
     ControlDisconnected = null;
     MessageReceived     = null;
 }
        public async void ConnectToGHUB_async()
        {
            var url = new Uri("ws://localhost:9010");

            var factory = new Func<ClientWebSocket>(() =>
            {
                var client = new ClientWebSocket();
                client.Options.UseDefaultCredentials = false;
                client.Options.SetRequestHeader("Origin", "file://");
                client.Options.SetRequestHeader("Pragma", "no-cache");
                client.Options.SetRequestHeader("Cache-Control", "no-cache");
                client.Options.SetRequestHeader("Sec-WebSocket-Extensions", "permessage-deflate; client_max_window_bits");
                client.Options.SetRequestHeader("Sec-WebSocket-Protocol", "json");
                return client;
            });

            _ws?.Dispose();
            _ws = new WebsocketClient(url, factory);
            _ws.MessageReceived.Subscribe(ParseSocketMsg);
            _ws.ErrorReconnectTimeout = TimeSpan.FromMilliseconds(500);
            _ws.ReconnectTimeout = null;

            Console.WriteLine($"Trying to connect to LGHUB_agent, at {url}");

            while (!_ws.IsRunning)
            {
                await _ws.Start();
            }

            Console.WriteLine($"Connected to LGHUB_agent");

            _ws.Send(JsonConvert.SerializeObject(new
            {
                msgId = "",
                verb = "SUBSCRIBE",
                path = "/devices/state/changed"
            }));

            _ws.Send(JsonConvert.SerializeObject(new
            {
                msgId = "",
                verb = "SUBSCRIBE",
                path = "/battery/state/changed"
            }));

            ScanDevices();
        }
Exemplo n.º 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());
        }
Exemplo n.º 21
0
 public void Dispose()
 {
     _connection?.Dispose();
     _client?.Dispose();
     _logger.LogInformation("Disposed");
 }
Exemplo n.º 22
0
 public void Dispose()
 {
     _client.Dispose();
 }
Exemplo n.º 23
0
 public void Disconnect()
 {
     client.Dispose();
 }
Exemplo n.º 24
0
 public Task Close()
 {
     _client.Dispose();
     return(Task.CompletedTask);
 }
        private async Task Connect(bool recoverSession = false)
        {
            var wsToken = await _rc.Post <WsToken>("/restapi/oauth/wstoken");

            var wsUri = $"{wsToken.uri}?access_token={wsToken.ws_access_token}";

            if (recoverSession)
            {
                wsUri = $"{wsUri}&wsc={_wsc.token}";
            }

            _ws = new WebsocketClient(new Uri(wsUri));
            _ws.ReconnectTimeout = TimeSpan.FromMinutes(2);

            _ws.ReconnectionHappened.Subscribe(async info =>
            {
                if (info.Type != ReconnectionType.Initial)
                {
                    _ws.Dispose();
                    await Connect(true);
                    if (!recoverSession || _connectionDetails.recoveryState == RecoveryState.Failed)
                    {
                        foreach (var subscription in _subscriptions)
                        {
                            if (subscription.SubscriptionInfo != null)
                            {
                                // otherwise it has been revoked explicitly
                                await subscription.SubScribe();
                            }
                        }
                    }
                }

                _ws.MessageReceived.Subscribe(responseMessage =>
                {
                    var wsgMessage = WsgMessage.Parse(responseMessage.Text);
                    if (_options.debugMode)
                    {
                        Console.WriteLine(
                            $"***WebSocket incoming message ({DateTime.Now.ToString(CultureInfo.CurrentCulture)}): ***" +
                            $"\n{JsonConvert.SerializeObject(wsgMessage, Formatting.Indented)}" +
                            "\n******");
                    }

                    MessageReceived?.Invoke(this, wsgMessage);
                });
            });

            MessageReceived += (sender, wsgMessage) =>
            {
                if (wsgMessage.meta.wsc != null && (_wsc == null ||
                                                    wsgMessage.meta.type ==
                                                    MessageType.ConnectionDetails &&
                                                    wsgMessage.body.GetType().GetProperty("recoveryState") != null ||
                                                    _wsc?.sequence < wsgMessage.meta.wsc.sequence))
                {
                    _wsc = wsgMessage.meta.wsc;
                }

                if (wsgMessage.meta.type == MessageType.ConnectionDetails)
                {
                    _connectionDetails = wsgMessage.body.ToObject <ConnectionDetails>();
                }
            };

            await _ws.Start();
        }
Exemplo n.º 26
0
 public void Dispose()
 {
     _client.Dispose();
     _resetEvent.Dispose();
 }
 // TODO: refactore
 public void Dispose()
 {
     _websocketClient?.Dispose();
 }