Ejemplo 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();
 }
Ejemplo n.º 2
0
 public Task CloseAsync()
 {
     if (_client == null)
     {
         throw new InvalidOperationException("Close failed, must connect first.");
     }
     else
     {
         _client.Stop(WebSocketCloseStatus.NormalClosure, string.Empty);
         _pingSource.Cancel();
         OnClosed?.Invoke(ServerCloseReason.ClosedByClient);
         return(Task.CompletedTask);
     }
 }
Ejemplo n.º 3
0
        public virtual async Task CloseAsync()
        {
            var client = WsClient;

            if (client?.IsRunning != true)
            {
                return;
            }

            // Close is kind of Send so Stop message should be sent under lock.
            await _wsLock.WaitAsync().ConfigureAwait(false);

            try
            {
                if (WsClient?.IsRunning != true)
                {
                    return;
                }

                CancelHeartbeats();
                await WsClient.Stop(WebSocketCloseStatus.NormalClosure, "").ConfigureAwait(false);
            }
            finally
            {
                _wsLock.Release();
            }
        }
Ejemplo n.º 4
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;
        }
Ejemplo n.º 5
0
        public async Task OnClose_ShouldWorkCorrectly()
        {
            using (IWebsocketClient client = new WebsocketClient(WebsocketUrl))
            {
                client.ReconnectTimeout = TimeSpan.FromSeconds(5);

                string            received           = null;
                var               receivedCount      = 0;
                var               receivedEvent      = new ManualResetEvent(false);
                var               disconnectionCount = 0;
                DisconnectionInfo disconnectionInfo  = null;

                client.MessageReceived.Subscribe(msg =>
                {
                    receivedCount++;
                    received = msg.Text;
                });

                client.DisconnectionHappened.Subscribe(x =>
                {
                    disconnectionCount++;
                    disconnectionInfo = x;
                });

                await client.Start();

#pragma warning disable 4014
                Task.Run(async() =>
#pragma warning restore 4014
                {
                    await Task.Delay(2000);
                    var success = await client.Stop(WebSocketCloseStatus.InternalServerError, "server error 500");
                    Assert.True(success);
                    receivedEvent.Set();
                });

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

                Assert.NotNull(received);
                Assert.Equal(1, receivedCount);

                var nativeClient = client.NativeClient;
                Assert.NotNull(nativeClient);
                Assert.Equal(1, disconnectionCount);
                Assert.Equal(DisconnectionType.ByUser, disconnectionInfo.Type);
                Assert.Equal(WebSocketCloseStatus.InternalServerError, disconnectionInfo.CloseStatus);
                Assert.Equal("server error 500", disconnectionInfo.CloseStatusDescription);
                Assert.Equal(WebSocketState.Aborted, nativeClient.State);
                Assert.Equal(WebSocketCloseStatus.InternalServerError, nativeClient.CloseStatus);
                Assert.Equal("server error 500", nativeClient.CloseStatusDescription);

                // check that reconnection is disabled
                await Task.Delay(7000);

                Assert.Equal(1, receivedCount);
            }
        }
Ejemplo n.º 6
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");
     }
 }
 public void Close(bool Abort = false)
 {
     if (_ws.IsRunning)
     {
         if (Abort)
         {
             _ws.Stop(WebSocketCloseStatus.NormalClosure, "Close");
         }
         else
         {
             _ws.Dispose();
         }
     }
 }
Ejemplo n.º 8
0
 /// <summary>
 /// 关闭Clash日志WebSocket
 /// </summary>
 public void CloseClashLog()
 {
     if (LoggingWebSocketClient != null)
     {
         try
         {
             LoggingWebSocketClient.Stop(WebSocketCloseStatus.Empty, string.Empty);
             LoggingWebSocketClient = null;
         }
         catch
         {
         }
     }
 }
Ejemplo n.º 9
0
 /// <summary>
 /// 关闭Clash连接WebSocket
 /// </summary>
 public void CloseClashConnection()
 {
     if (ConnectionWebSocketClient != null)
     {
         try
         {
             ConnectionWebSocketClient.Stop(WebSocketCloseStatus.Empty, string.Empty);
             ConnectionWebSocketClient = null;
         }
         catch
         {
         }
     }
 }
Ejemplo n.º 10
0
 /// <summary>
 /// 关闭Clash流量WebSocket
 /// </summary>
 public void CloseClashTraffic()
 {
     if (TrafficWebSocketClient != null)
     {
         try
         {
             TrafficWebSocketClient.Stop(WebSocketCloseStatus.Empty, string.Empty);
             TrafficWebSocketClient = null;
         }
         catch
         {
         }
     }
 }
Ejemplo n.º 11
0
        public static void Check(int port, Action <OverlayResponse> callback)
        {
            OverlayResponse response = new OverlayResponse(port);
            WebsocketClient overlay  = new WebsocketClient(new Uri($"ws://127.0.0.1:{port}/?v=1&encoding=json"), () =>
            {
                ClientWebSocket ws = new ClientWebSocket();
                ws.Options.SetRequestHeader("Origin", "https://discordapp.com");
                return(ws);
            })
            {
                IsReconnectionEnabled = false
            };

            overlay.DisconnectionHappened.Subscribe(disconnect =>
            {
                if (disconnect.Exception != null)
                {
                    response.Success = false;
                    callback(response);
                }
            });
            overlay.MessageReceived.Subscribe(message =>
            {
                JsonElement msg = JsonDocument.Parse(message.Text).RootElement;
                if (msg.GetProperty("cmd").GetString() == "DISPATCH" && msg.GetProperty("evt").GetString() == "READY")
                {
                    response.ReleaseChannel = OverlayResponse.ReleaseChannels[msg.GetProperty("data").GetProperty("config").GetProperty("api_endpoint").GetString()];
                    overlay.Send("{\"cmd\":\"SUBSCRIBE\",\"args\":{},\"evt\":\"OVERLAY\",\"nonce\":\"discord-fix-your-software\"}");
                }
                else if (msg.GetProperty("cmd").GetString() == "SUBSCRIBE" && msg.GetProperty("data").GetProperty("evt").GetString() == "OVERLAY")
                {
                    overlay.Send("{\"cmd\":\"OVERLAY\",\"args\":{\"type\":\"CONNECT\",\"pid\":-1},\"nonce\":\"pid-validation-and-blocking-overlay-connections-if-overlay-is-disabled\"}");
                }
                else if (msg.GetProperty("cmd").GetString() == "DISPATCH" && msg.GetProperty("data").GetProperty("type").GetString() == "STORAGE_SYNC")
                {
                    // there's a few small bits of interesting information here but nothing worth a lot
                    response.StorageStates = msg.GetProperty("data").GetProperty("states");
                }
                else if (msg.GetProperty("cmd").GetString() == "DISPATCH" && msg.GetProperty("data").GetProperty("type").GetString() == "DISPATCH" && msg.GetProperty("data").GetProperty("payloads")[0].GetProperty("type").GetString() == "OVERLAY_INITIALIZE")
                {
                    // quality software
                    response.Success           = true;
                    response.InitializePayload = msg.GetProperty("data").GetProperty("payloads")[0];
                    overlay.Stop(WebSocketCloseStatus.EndpointUnavailable, "");
                    callback(response);
                }
            });
            overlay.Start();
        }
Ejemplo n.º 12
0
        public async Task Disconnect()
        {
            _restoreConnection = false;

            if (_socketConnection.IsRunning)
            {
                await CloseSubscriptions();
            }

            await _socketConnection.Stop(WebSocketCloseStatus.NormalClosure, String.Empty);

            _socketConnection = null;

            Error = null;
        }
 /// <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 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
        }
Ejemplo n.º 15
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.");
        }
Ejemplo n.º 16
0
        public async Task DisabledReconnecting_ShouldWorkAsExpected()
        {
            using (IWebsocketClient client = new WebsocketClient(WebsocketUrl))
            {
                var receivedCount = 0;
                var receivedEvent = new ManualResetEvent(false);

                client.IsReconnectionEnabled = false;
                client.ReconnectTimeout      = TimeSpan.FromSeconds(2);

                client.MessageReceived.Subscribe(msg =>
                {
                    receivedCount++;
                    if (receivedCount >= 2)
                    {
                        receivedEvent.Set();
                    }
                });

                await client.Start();

                await Task.Delay(5000);

                await client.Stop(WebSocketCloseStatus.Empty, string.Empty);

                await Task.Delay(5000);

                await client.Start();

                await Task.Delay(1000);

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

                Assert.Equal(2, receivedCount);
            }
        }
Ejemplo n.º 17
0
 public async Task DisconnectAsync()
 {
     await _client.Stop(WebSocketCloseStatus.NormalClosure, nameof(WebSocketCloseStatus.NormalClosure));
 }
 void Disconnect(ushort code, string reason, bool reconnect)
 {
     Logger.Warning(this, $"Disconnecting: {code}", reason);
     socket.Stop((WebSocketCloseStatus)code, reason);
     OnDisconnected(reconnect);
 }
Ejemplo n.º 19
0
 public override async Task EndProcess()
 {
     await _client.Stop(System.Net.WebSockets.WebSocketCloseStatus.Empty, "");
 }
Ejemplo n.º 20
0
 /// <inheritdoc />
 public async Task <bool> DisconnectAsync()
 {
     return(await _webSocket.Stop(WebSocketCloseStatus.NormalClosure,
                                  "User requested to close the connection."));
 }
Ejemplo n.º 21
0
 public async Task Close()
 {
     await client.Stop(WebSocketCloseStatus.NormalClosure, "");
 }
Ejemplo n.º 22
0
 public void Disconnect()
 {
     client.Stop(WebSocketCloseStatus.NormalClosure, "Manual disconnection");
 }