Beispiel #1
0
        protected async virtual Task ProcessPacket(IWebSocketClient client, string header, string content)
        {
            _logger.Write(LogType.Normal, "Pack(" + header + "): " + content + "\r\n");

            try
            {
                // implement json parse error exception so that we dont crash the entire app but only disconnect this client
                var data = JsonParser.Parse <JsonObject>(content);
                if (header == "new")
                {
                    var packageName           = data.GetMember <JsonString>("packageName").Value;
                    var instanceConfiguration = InstanceConfiguration.CreateDefault(_settings);

                    var instanceId = _hostClient.CreateInstance(
                        packageName,
                        instanceConfiguration);

                    await Broadcast("new", new
                    {
                        instanceId  = instanceId,
                        packageName = packageName
                    });
                }
            }
            catch (Framework.Json.JsonException ex)
            {
                _logger.Write(
                    LogType.Error,
                    $"[{header}] Json protocol error: ({ex.GetType().Name}) '{ex.Message}' in packet: {content}");
            }
        }
Beispiel #2
0
        public async Task ConnectAsync(CancellationToken cancellationToken)
        {
            if (_cancellationTokenSource.IsCancellationRequested)
            {
                return;
            }

            using (await _asyncLock.WaitAsync(cancellationToken).ConfigureAwait(false))
            {
                _webSocketClient?.DisposeExceptionSafe(_logger);
                _webSocketClient = null;

                var webSocketClient  = _componentContext.Resolve <IWebSocketClient>();
                var rtmStartResponse = await _slackService.CallApiAsync <RtmStartApiResponse>(
                    "rtm.start",
                    new Dictionary <string, string>
                {
                    { "simple_latest", "true" },
                    { "no_unreads", "true" }
                },
                    cancellationToken)
                                       .ConfigureAwait(false);

                await webSocketClient.ConnectAsync(rtmStartResponse.Url, cancellationToken).ConfigureAwait(false);

                _self            = rtmStartResponse.Self;
                _webSocketClient = webSocketClient;
                _webSocketClient.Messages.Subscribe(Received, Error); // No need to handle disposable
            }
        }
Beispiel #3
0
        /// <summary>
        /// Wait until web socket is open (connected).
        /// </summary>
        /// <param name="webSocket"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static async Task WaitUntilOpenAsync(this IWebSocketClient webSocket, CancellationToken token = default)
        {
            Throw.IfNull(webSocket, nameof(webSocket));

            var tcs = new TaskCompletionSource <bool>(TaskCreationOptions.RunContinuationsAsynchronously);

            EventHandler <EventArgs> handler = (s, e) => tcs.SetResult(true);

            webSocket.Open += handler;

            try
            {
                if (token.IsCancellationRequested || webSocket.IsOpen)
                {
                    return;
                }

                if (token.CanBeCanceled)
                {
                    using (token.Register(() => tcs.SetCanceled()))
                    {
                        await tcs.Task.ConfigureAwait(false);
                    }
                }
                else
                {
                    await tcs.Task.ConfigureAwait(false);
                }
            }
            finally { webSocket.Open -= handler; }
        }
Beispiel #4
0
        private async Task VoiceWS_SocketClosed(IWebSocketClient client, SocketCloseEventArgs e)
        {
            this.Discord.Logger.LogDebug(VoiceNextEvents.VoiceConnectionClose, "Voice WebSocket closed ({0}, '{1}')", e.CloseCode, e.CloseMessage);

            // generally this should not be disposed on all disconnects, only on requested ones
            // or something
            // otherwise problems happen
            //this.Dispose();

            if (e.CloseCode == 4006 || e.CloseCode == 4009)
            {
                this.Resume = false;
            }

            if (!this.IsDisposed)
            {
                this.TokenSource.Cancel();
                this.TokenSource              = new CancellationTokenSource();
                this.VoiceWs                  = this.Discord.Configuration.WebSocketClientFactory(this.Discord.Configuration.Proxy);
                this.VoiceWs.Disconnected    += this.VoiceWS_SocketClosed;
                this.VoiceWs.MessageReceived += this.VoiceWS_SocketMessage;
                this.VoiceWs.Connected       += this.VoiceWS_SocketOpened;

                if (this.Resume) // emzi you dipshit
                {
                    await this.ConnectAsync().ConfigureAwait(false);
                }
            }
        }
Beispiel #5
0
        public async Task Connect(string name, string uri)
        {
            _close = false;
            //var channel = Channel.CreateBounded<SentMessage>(new BoundedChannelOptions(5) { SingleReader = true, SingleWriter = false });
            _webSocketClient = new WebSocketClient(new Uri(uri), logger: _logger, sender: new SingleQueueSender(), name: name);

            _disposables = new CompositeDisposable();

            BuildStream(_disposables);

            await _webSocketClient.ConnectAsync();

            _webSocketClient.Send(Encoding.UTF8.GetBytes(name));

            // for debug code.
            //_ = Task.Run(async () =>
            //{
            //    int i = 0;
            //    while (!_close)
            //    {
            //        this.Send("continuous sending test." + ++i);
            //        await Task.Delay(TimeSpan.FromMilliseconds(1));
            //    }
            //});
        }
Beispiel #6
0
 public PubsubRequest(IWebSocketClient client, string bucketId, byte[] data, bool isText, RequestOptions options)
 {
     Client  = client;
     Data    = data;
     IsText  = isText;
     Options = options;
 }
Beispiel #7
0
        public POCViewModel(IWebSocketClient client, string clientName, BoundingBoxRequest bbr, string clientIndex)
        {
            this.client     = client;
            this.ClientName = clientName;
            IDToEntity      = new Dictionary <string, Entity>();

            triggerStatisticsCollector        = new NumberStatisticsCollector();
            redisStatisticsCollector          = new NumberStatisticsCollector();
            entitiesAmountStatisticsCollector = new NumberStatisticsCollector();

            csvExporter = new CsvHelperCsvExporter(clientIndex);

            generator = new ZoomChangeGenerator(this, bbr);
            generator.Start();

            workQueue = new BlockingCollection <DistributionWorkItem>();
            workers   = new List <DistributionWorker>();

            for (int i = 0; i < ConfigData.Instance.Workers; i++)
            {
                var worker = new DistributionWorker(client, triggerStatisticsCollector, redisStatisticsCollector, entitiesAmountStatisticsCollector, workQueue);
                workers.Add(worker);
                worker.Start();
            }
        }
Beispiel #8
0
        private async Task VoiceWS_SocketMessage(IWebSocketClient client, SocketMessageEventArgs e)
        {
            if (!(e is SocketTextMessageEventArgs et))
            {
                this.Discord.Logger.LogCritical(VoiceNextEvents.VoiceGatewayError, "Discord Voice Gateway sent binary data - unable to process");
                return;
            }

            if (this.Discord.Configuration.MinimumLogLevel == LogLevel.Trace)
            {
                var cs = new MemoryStream();

                await et.Message.CopyToAsync(cs).ConfigureAwait(false);

                cs.Seek(0, SeekOrigin.Begin);
                et.Message.Seek(0, SeekOrigin.Begin);

                using var sr = new StreamReader(cs, Utilities.UTF8);

                this.Discord.Logger.LogTrace(VoiceNextEvents.VoiceWsRx, await sr.ReadToEndAsync().ConfigureAwait(false));
            }

            var j = await DiscordJson.LoadJObjectAsync(et.Message).ConfigureAwait(false);

            await this.HandleDispatch(j).ConfigureAwait(false);
        }
        /// <summary>
        /// 初始化实时消息客户端
        /// </summary>
        /// <param name="config"></param>
        public AVRealtime(Configuration config)
        {
            lock (mutex)
            {
                if ((int)config.OfflineMessageStrategy == 0)
                {
                    config.OfflineMessageStrategy = OfflineMessageStrategy.UnreadAck;
                }

                CurrentConfiguration = config;
                if (CurrentConfiguration.WebSocketClient != null)
                {
                    webSocketController = CurrentConfiguration.WebSocketClient;
                }
                if (CurrentConfiguration.SignatureFactory != null)
                {
                    this.SignatureFactory = CurrentConfiguration.SignatureFactory;
                }
                ReconnectOptions = new AVIMReconnectOptions()
                {
                    Interval = 5,
                    Retry    = 120
                };


                RegisterMessageType <AVIMMessage>();
                RegisterMessageType <AVIMTypedMessage>();
                RegisterMessageType <AVIMTextMessage>();
                RegisterMessageType <AVIMImageMessage>();
                RegisterMessageType <AVIMAudioMessage>();
                RegisterMessageType <AVIMVideoMessage>();
                RegisterMessageType <AVIMFileMessage>();
                RegisterMessageType <AVIMLocationMessage>();
            }
        }
Beispiel #10
0
        protected async virtual Task OnWebSocketData(IWebSocketClient client, string data)
        {
            _logger.Write(LogType.Normal, "OnWebSocketData: " + data + "\r\n");

            var buffer = client.Buffer.ToString() + data;
            int pos;

            while ((pos = buffer.IndexOf('|', client.Buffer.Length)) != -1)
            {
                var header = buffer.Substring(0, pos);
                buffer = buffer.Substring(pos + 1);

                if ((pos = header.IndexOf(' ')) != -1)
                {
                    await ProcessPacket(
                        client,
                        header.Substring(0, pos).ToLower(),
                        header.Substring(pos + 1));
                }
                else
                {
                    await ProcessPacket(client, header.ToLower(), string.Empty);
                }
            }
        }
Beispiel #11
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="client"></param>
        /// <param name="logger"></param>
        protected BinanceWebSocketClient(IWebSocketClient client, ILogger logger = null)
        {
            Throw.IfNull(client, nameof(client));

            WebSocket = client;
            Logger    = logger;
        }
Beispiel #12
0
 public void Disconnect()
 {
     if (mConn != null)
     {
         mConn.Disconnect();
         mConn = null;
     }
 }
 public IWebSocketSubscriber CreateSubscriber(IMessageHandler messageHandler, IWebSocketClient webSocketClient)
 {
     return(new QueueWebSocketSubscriber(
                messageHandler,
                webSocketClient,
                new WebSocketDestinationMessagePipeline(messageHandler, webSocketClient),
                this.settings));
 }
        public void Disconnect()
        {
            _webSocketClient?.Close();
            _webSocketClient = null;

            _userInitiatedDisconnect = true;
            _hasReceivedConnected    = false;
        }
Beispiel #15
0
        // handlers
        protected async virtual Task OnWebSocketOpen(IWebSocketClient client)
        {
            _logger.Write(LogType.Normal, "OnWebSocketOpen (cli: " + _clients.Count + ")\r\n");

            //await client.Send("new {\"instanceId\":\"531853186\",\"packageName\":\"hello world\"}|");

            await client.Send("test", client);
        }
    public IWebSocketClientTransportPipeline New(IWebSocketClient webSocketClient)
    {
        if (webSocketClient.State != WebSocketState.Open)
        {
            throw new ApplicationException("Unexpected state of WebSocketClient, should be 'Open'");
        }

        return(new WebSocketClientTransportPipeline(webSocketClient));
    }
Beispiel #17
0
        public void Reconnect()
        {
            _webSocketClient?.Close();

            _userInitiatedDisconnect = false;
            _hasReceivedConnected    = false;
            _webSocketClient         = _webSocketClientFactory(_hostUri, _webSocketClientCallback);
            _webSocketClient.Open();
        }
 public WebSocketChat(IWebSocketClient client, ILogFactory logger = null)
     : base(logger)
 {
     _client            = client;
     _client.Connected += OnConnected;
     _client.Close     += OnClose;
     _client.Error     += OnError;
     _client.Message   += OnMessage;
 }
 public void OnOpen(IWebSocketClient client)
 {
   _client = (WebSocketHandler)client;
   lock (ActiveSockets)
   {
     ActiveSockets.Add(_client);
   }
   Debug.Print("Connected new websocket client");
 }
        private async Task WebSocket_OnConnect(IWebSocketClient client, SocketEventArgs ea)
        {
            this.Discord.Logger.LogDebug(LavalinkEvents.LavalinkConnected, "Connection to Lavalink node established");

            if (this.Configuration.ResumeKey != null)
            {
                await this.SendPayloadAsync(new LavalinkConfigureResume(this.Configuration.ResumeKey, this.Configuration.ResumeTimeout)).ConfigureAwait(false);
            }
        }
Beispiel #21
0
        public WebSocketClientHandler(IWebSocketClient client,
                                      WebSocketClientHandshaker handshaker)
        {
            _client = client;
            _logger = client.LoggerFactory.CreateLogger <WebSocketClientHandler>();

            _handshaker       = handshaker;
            _completionSource = new TaskCompletionSource();
        }
Beispiel #22
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="client"></param>
        /// <param name="logger">The logger (optional).</param>
        public BinanceWebSocketStream(IWebSocketClient client, ILogger <BinanceWebSocketStream> logger = null)
        {
            Throw.IfNull(client, nameof(client));

            Client  = client;
            _logger = logger;

            _subscribers = new Dictionary <string, ICollection <Action <WebSocketStreamEventArgs> > >();
        }
Beispiel #23
0
        private IWebSocketClient GetInstance()
        {
            if (this.Client == null)
            {
                this.Client = new WS4NetClient();
            }

            return(this.Client);
        }
        public Task RegisterWebSocket(IWebSocketClient webSocketClient)
        {
            // No keeping track of the clients yet...

            var subscriber = this.webSocketSubscriberFactory.CreateSubscriber(this, webSocketClient);

            subscriber.Subscribe();

            return(Task.CompletedTask);
        }
 public FeedManager(
     ILogger <FeedManager> logger,
     IWebSocketClient webSocketClient,
     IMessageDumper messageDumper
     )
 {
     this.logger          = logger;
     this.webSocketClient = webSocketClient;
     this.messageDumper   = messageDumper;
 }
        public DiscordRpcApiClient(string clientId, string userAgent, string origin, RestClientProvider restClientProvider, WebSocketProvider webSocketProvider,
                                   RetryMode defaultRetryMode = RetryMode.AlwaysRetry, JsonSerializer serializer = null)
            : base(restClientProvider, userAgent, defaultRetryMode, serializer)
        {
            _connectionLock = new SemaphoreSlim(1, 1);
            _clientId       = clientId;
            _origin         = origin;

            _requests = new ConcurrentDictionary <Guid, RpcRequest>();

            _webSocketClient = webSocketProvider();
            //_webSocketClient.SetHeader("user-agent", DiscordConfig.UserAgent); (Causes issues in .Net 4.6+)
            _webSocketClient.SetHeader("origin", _origin);
            _webSocketClient.BinaryMessage += async(data, index, count) =>
            {
                using (var compressed = new MemoryStream(data, index + 2, count - 2))
                    using (var decompressed = new MemoryStream())
                    {
                        using (var zlib = new DeflateStream(compressed, CompressionMode.Decompress))
                            zlib.CopyTo(decompressed);
                        decompressed.Position = 0;
                        using (var reader = new StreamReader(decompressed))
                            using (var jsonReader = new JsonTextReader(reader))
                            {
                                var msg = _serializer.Deserialize <API.Rpc.RpcFrame>(jsonReader);
                                await _receivedRpcEvent.InvokeAsync(msg.Cmd, msg.Event, msg.Data).ConfigureAwait(false);

                                if (msg.Nonce.IsSpecified && msg.Nonce.Value.HasValue)
                                {
                                    ProcessMessage(msg);
                                }
                            }
                    }
            };
            _webSocketClient.TextMessage += async text =>
            {
                using (var reader = new StringReader(text))
                    using (var jsonReader = new JsonTextReader(reader))
                    {
                        var msg = _serializer.Deserialize <API.Rpc.RpcFrame>(jsonReader);
                        await _receivedRpcEvent.InvokeAsync(msg.Cmd, msg.Event, msg.Data).ConfigureAwait(false);

                        if (msg.Nonce.IsSpecified && msg.Nonce.Value.HasValue)
                        {
                            ProcessMessage(msg);
                        }
                    }
            };
            _webSocketClient.Closed += async ex =>
            {
                await DisconnectAsync().ConfigureAwait(false);

                await _disconnectedEvent.InvokeAsync(ex).ConfigureAwait(false);
            };
        }
Beispiel #27
0
        public JsonRpc(IWebSocketClient wsc, ILogger logger, JsonRpcParams param)
        {
            _wsc           = wsc;
            _logger        = logger;
            _jsonRpcParams = param;

            _responses     = new ConcurrentDictionary <int, BufferBlock <JObject> >();
            _subscriptions = new ConcurrentDictionary <int, IWebSocketMessageObserver>();
            _pendingSubscriptionUpdates = new ConcurrentDictionary <int, JObject>();
            _wsc.RegisterMessageObserver(this);
        }
        /// <summary>
        /// The add service async.
        /// </summary>
        /// <param name="client">
        /// The client.
        /// </param>
        public Task RunServiceAsync(IWebSocketClient client)
        {
            if (client.IsConnected)
            {
                var service = new Service(client, this.messageHandler);
                this.availableServices.Enqueue(service);
                return(service.RunServiceAsync());
            }

            return(Task.CompletedTask);
        }
Beispiel #29
0
        public async Task DisconnectAsync(CancellationToken cancellationToken)
        {
            using (await _asyncLock.WaitAsync(cancellationToken).ConfigureAwait(false))
            {
                _logger.Verbose("Disconnecting Slack");

                _cancellationTokenSource.Cancel();
                _webSocketClient?.DisposeExceptionSafe(_logger);
                _webSocketClient = null;
            }
        }
        public async void StartExecution()
        {
            foreach (IWebSocketClient webSocketClient in this.webSocketClients)
            {
                IWebSocketClient tempWebSocketClient = webSocketClient;
                Task             task = Task.Factory.StartNew(() => this.ExecuteWebSocketClient(tempWebSocketClient), creationOptions: TaskCreationOptions.LongRunning);
                this.tasks.Add(task);
            }

            await Task.WhenAll(this.tasks);
        }
Beispiel #31
0
        private Task VoiceWS_SocketMessage(IWebSocketClient client, SocketMessageEventArgs e)
        {
            if (!(e is SocketTextMessageEventArgs et))
            {
                this.Discord.Logger.LogCritical(VoiceNextEvents.VoiceGatewayError, "Discord Voice Gateway sent binary data - unable to process");
                return(Task.CompletedTask);
            }

            this.Discord.Logger.LogTrace(VoiceNextEvents.VoiceWsRx, et.Message);
            return(this.HandleDispatch(JObject.Parse(et.Message)));
        }
        public void Initialise(ConnectionInformation connectionInformation)
        {
            SlackKey = connectionInformation.SlackKey;
            Team = connectionInformation.Team;
            Self = connectionInformation.Self;
            _userCache = connectionInformation.Users;
            _connectedHubs = connectionInformation.SlackChatHubs;

            _webSocketClient = connectionInformation.WebSocket;
            _webSocketClient.OnClose += (sender, args) =>
            {
                ConnectedSince = null;
                RaiseOnDisconnect();
            };

            _webSocketClient.OnMessage += async (sender, message) => await ListenTo(message);

            ConnectedSince = DateTime.Now;
        }
Beispiel #33
0
        public async Task DisconnectAsync(CancellationToken cancellationToken)
        {
            using (await _asyncLock.WaitAsync(cancellationToken).ConfigureAwait(false))
            {
                _logger.Verbose("Disconnecting Slack");

                _cancellationTokenSource.Cancel();
                _webSocketClient?.DisposeExceptionSafe(_logger);
                _webSocketClient = null;
            }
        }
 public AVIMCommandRunner(IWebSocketClient webSocketClient)
 {
     this.webSocketClient = webSocketClient;
 }
Beispiel #35
0
        public async Task ConnectAsync(CancellationToken cancellationToken)
        {
            if (_cancellationTokenSource.IsCancellationRequested)
            {
                return;
            }

            using (await _asyncLock.WaitAsync(cancellationToken).ConfigureAwait(false))
            {
                _webSocketClient?.DisposeExceptionSafe(_logger);
                _webSocketClient = null;

                var webSocketClient = _componentContext.Resolve<IWebSocketClient>();
                var rtmStartResponse = await _slackService.CallApiAsync<RtmStartApiResponse>(
                    "rtm.start",
                    new Dictionary<string, string>
                    {
                        {"simple_latest", "true"},
                        {"no_unreads", "true"}
                    },
                    cancellationToken)
                    .ConfigureAwait(false);

                await webSocketClient.ConnectAsync(rtmStartResponse.Url, cancellationToken).ConfigureAwait(false);

                _self = rtmStartResponse.Self;
                _webSocketClient = webSocketClient;
                _webSocketClient.Messages.Subscribe(Received, Error); // No need to handle disposable
            }
        }