Beispiel #1
0
        public async Task <bool> GetWsStatusAsync(int nodeId)
        {
            var nodeUrl = this.db.Nodes
                          .Where(x => x.Id == nodeId)
                          .Select(x => $"ws://{x.Url}:10334")
                          .FirstOrDefault();

            var websocket = new System.Net.WebSockets.ClientWebSocket();
            var success   = false;

            try
            {
                await websocket.ConnectAsync(new System.Uri(nodeUrl), CancellationToken.None);

                success = websocket.State == System.Net.WebSockets.WebSocketState.Open;
                await websocket.CloseAsync(System.Net.WebSockets.WebSocketCloseStatus.NormalClosure, null, CancellationToken.None);
            }
            catch (Exception e)
            {
                Log.Error("WS connection CloseAsync() ", e);
            }
            finally
            {
                websocket.Dispose();
            }

            return(success);
        }
        public async void StopConnect(System.Threading.CancellationToken?token = null)
        {
            var _token = token ?? GetDefaultCancellationToken();

            Log(LogType.Info, "开始断开连接服务器");

            if (this._isConnect)
            {
                await clientWebSocket.CloseAsync(System.Net.WebSockets.WebSocketCloseStatus.NormalClosure, "", _token);
            }
        }
Beispiel #3
0
        private void ReadAndUpdateData()
        {
            // Works better if new data is allways loaded
            bool update = false;

            if (update)
            {
                string msgSubscribeDiff  = String.Format("{{\"event\": \"bts:subscribe\",\"data\": {{\"channel\": \"diff_order_book_{0}\"}}}}\r\n", currencyPair);
                string msgUnubscribeDiff = String.Format("{{\"event\": \"bts:unsubscribe\",\"data\": {{\"channel\": \"diff_order_book_{0}\"}}}}\r\n", currencyPair);

                readData = true;
                cws.SendAsync(new ArraySegment <byte>(Encoding.UTF8.GetBytes(msgSubscribeDiff)), System.Net.WebSockets.WebSocketMessageType.Binary, true, token);
                while (readData)
                {
                    string   msg  = ReadMsgSync(token);
                    JsonData data = System.Text.Json.JsonSerializer.Deserialize <JsonData>(msg);
                    MoveJsonDataToTransactions(data);
                    //Console.WriteLine(msg);
                }
                cws.SendAsync(new ArraySegment <byte>(Encoding.UTF8.GetBytes(msgUnubscribeDiff)), System.Net.WebSockets.WebSocketMessageType.Text, true, token);
            }
            else
            {
                string msgSubscribe  = String.Format("{{\"event\": \"bts:subscribe\",\"data\": {{\"channel\": \"order_book_{0}\"}}}}\r\n", currencyPair);
                string msgUnubscribe = String.Format("{{\"event\": \"bts:unsubscribe\",\"data\": {{\"channel\": \"order_book_{0}\"}}}}\r\n", currencyPair);

                readData = true;
                cws.SendAsync(new ArraySegment <byte>(Encoding.UTF8.GetBytes(msgSubscribe)), System.Net.WebSockets.WebSocketMessageType.Binary, true, token);
                string reply = ReadMsgSync(token);
                while (readData)
                {
                    string   msg  = ReadMsgSync(token);
                    JsonData data = System.Text.Json.JsonSerializer.Deserialize <JsonData>(msg);
                    if (((data?.data ?? null) != null) && (data.data.asks != null) && (data.data.bids != null))
                    {
                        MoveJsonDataToTransactions(data, false);
                    }
                }
                cws.SendAsync(new ArraySegment <byte>(Encoding.UTF8.GetBytes(msgUnubscribe)), System.Net.WebSockets.WebSocketMessageType.Text, true, token);
            }
            cws.CloseAsync(System.Net.WebSockets.WebSocketCloseStatus.NormalClosure, "", token);
        }
        private async System.Threading.Tasks.Task RunClient(string url, IObserver <PIItemsStreamValues> observer, System.Threading.CancellationToken cancellationToken)
        {
            Uri uri = new Uri(url);

            System.Net.WebSockets.WebSocketReceiveResult receiveResult;
            byte[] receiveBuffer = new byte[65536];
            ArraySegment <byte> receiveSegment = new ArraySegment <byte>(receiveBuffer);

            using (System.Net.WebSockets.ClientWebSocket webSocket = new System.Net.WebSockets.ClientWebSocket())
            {
                if ((this.Configuration.ApiClient.Username == null) || (this.Configuration.ApiClient.Password == null))
                {
                    webSocket.Options.UseDefaultCredentials = true;
                }
                else
                {
                    webSocket.Options.Credentials = new System.Net.NetworkCredential(this.Configuration.ApiClient.Username, this.Configuration.ApiClient.Password);
                }

                try
                {
                    await webSocket.ConnectAsync(uri, System.Threading.CancellationToken.None);
                }
                catch (System.Net.WebSockets.WebSocketException e)
                {
                    Console.WriteLine("Could not connect to server.");
                    observer.OnError(e);
                    return;
                }
                while (true)
                {
                    try
                    {
                        receiveResult = await webSocket.ReceiveAsync(receiveSegment, cancellationToken);
                    }
                    catch (OperationCanceledException)
                    {
                        observer.OnCompleted();
                        break;
                    }

                    if (receiveResult.MessageType != System.Net.WebSockets.WebSocketMessageType.Text)
                    {
                        await webSocket.CloseAsync(
                            System.Net.WebSockets.WebSocketCloseStatus.InvalidMessageType,
                            "Message type is not text.",
                            System.Threading.CancellationToken.None);

                        observer.OnError(new Exception("Message type is not text."));
                        return;
                    }
                    else if (receiveResult.Count > receiveBuffer.Length)
                    {
                        await webSocket.CloseAsync(
                            System.Net.WebSockets.WebSocketCloseStatus.InvalidPayloadData,
                            "Message is too long.",
                            System.Threading.CancellationToken.None);

                        observer.OnError(new Exception("Message is too long."));
                        return;
                    }
                    try
                    {
                        string message             = System.Text.Encoding.UTF8.GetString(receiveBuffer, 0, receiveResult.Count);
                        PIItemsStreamValues values = Newtonsoft.Json.JsonConvert.DeserializeObject <PIItemsStreamValues>(message);
                        observer.OnNext(values);
                    }
                    catch (Exception e)
                    {
                        observer.OnError(e);
                    }
                }
                await webSocket.CloseAsync(
                    System.Net.WebSockets.WebSocketCloseStatus.NormalClosure,
                    "Closing connection.",
                    System.Threading.CancellationToken.None);

                observer.OnCompleted();
            }
        }