public void RunScript(string feedtoken, string clientcode, string script, string task)
        {
            string strwatchlistscrips = "";

            if (feedtoken != "" && clientcode != "")
            {
                if (_ws.IsStarted)
                {
                    try
                    {
                        if (task != null && task != "")
                        {
                            if (task == "mw" || task == "sfi" || task == "dp")
                            {
                                strwatchlistscrips = script;   //"nse_cm|2885&nse_cm|1594&nse_cm|11536";
                                string scriptReq = "{\"task\":\"mw\",\"channel\":\"" + strwatchlistscrips + "\",\"token\":\"" + feedtoken + "\",\"user\": \"" + clientcode + "\",\"acctid\":\"" + clientcode + "\"}";
                                _ws.Send(scriptReq);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }
        }
예제 #2
0
        public async Task <ConnectionCode> CreateGame(Player player, ImmutableArray <Ship> ships)
        {
            var         completionSource = new TaskCompletionSource <ConnectionCode>();
            IDisposable subscription     = null;

            subscription = _socket.MessageReceived.Subscribe(msg => {
                var connectionResult = _serializer.DeserializeDynamic(msg.Text);
                switch ((string)connectionResult["message_type"])
                {
                case "connection_code":
                    var connectionCode = _serializer.DeserializeObject <ConnectionCode>(connectionResult);
                    completionSource.SetResult(connectionCode);
                    break;

                case "game_connected":
                    var result = _serializer.DeserializeObject <ConnectionToGameResult>(connectionResult);
                    subscription.Dispose();
                    _reconnectSubscription.Dispose();
                    GameCreated?.Invoke(this, new(_socket, result.Go, result.Enemy));
                    break;

                default:
                    throw new("Unexpected message type");
                }
            });
            await Connect();

            var message = new CreateGameMessage(new(player, ships, null));
            var text    = _serializer.Serialize(message);

            _socket.Send(text);
            return(await completionSource.Task);
        }
예제 #3
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);
            }
        }
예제 #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;
        }
예제 #5
0
        static void Main(string[] args)
        {
            const int BUFFER_SIZE = 16000;
            string    baseUrl     = "wss://api.amerandish.com/v1";
            string    actionUrl   = "/speech/asrlive";
            string    authKey     = "<YOUR_API_KEY>";

            string filePath = @"<YOUR_WAV_FILE_PATH>";

            string url = baseUrl + actionUrl + "?jwt=" + authKey;

            var bytes     = File.ReadAllBytes(filePath);
            var base64    = Convert.ToBase64String(bytes);
            var exitEvent = new ManualResetEvent(false);
            var factory   = new Func <ClientWebSocket>(() =>
            {
                var client = new ClientWebSocket
                {
                    Options =
                    {
                        KeepAliveInterval = TimeSpan.FromSeconds(5),
                    }
                };
                return(client);
            });

            using (var client = new WebsocketClient(new Uri(url), factory)){
                client.ReconnectTimeout = TimeSpan.FromSeconds(30);
                client.MessageReceived.Subscribe(msg => {
                    try
                    {
                        var model = ResponseModel.FromJson(msg.ToString());
                        Console.WriteLine(model.ToJson());
                    }
                    catch (System.Exception e)
                    {
                        Console.WriteLine(e);
                    }
                });

                client.Start().Wait();
                for (int index = 0; index < base64.Length; index += BUFFER_SIZE)
                {
                    if (index + BUFFER_SIZE < base64.Length)
                    {
                        Console.WriteLine(string.Format("send {0} -> {1}", index, index + BUFFER_SIZE));
                        client.Send(Encoding.UTF8.GetBytes(base64.Substring(index, BUFFER_SIZE)));
                    }
                    else
                    {
                        Console.WriteLine(string.Format("send {0} -> {1}", index, base64.Length));
                        client.Send(Encoding.UTF8.GetBytes(base64.Substring(index)));
                    }
                }
                exitEvent.WaitOne();
            }
        }
 public void ScanDevices()
 {
     _ws.Send(JsonConvert.SerializeObject(new
     {
         msgId = "",
         verb = "GET",
         path = "/devices/list"
     }));
 }
예제 #7
0
        internal Task SendFetchAsync(IDocumentInternal doc)
        {
            var msg = new JObject(
                new JProperty("a", "f"),
                new JProperty("c", doc.Collection),
                new JProperty("d", doc.Id),
                new JProperty("v", doc.Version < 0 ? null : (int?)doc.Version));

            return(_socket.Send(msg.ToString()));
        }
예제 #8
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"
            }));
        }
예제 #9
0
 private void DiscordBotLogin()
 {
     try
     {
         if (discordWebSocket.IsRunning)
         {
             discordWebSocket.Send("login|" + AppSettingsSerializer.Instance.AppSettings.DiscordBotToken);
         }
     }
     catch (Exception e)
     {
         ErrorLogger.Append(e);
     }
 }
예제 #10
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();
        }
예제 #11
0
        public void Connect()
        {
            if (!config.UseIntroducer)
            {
                Log.Debug($"Introducer peer discovery service will not be used.");
                return;
            }

            client.Name = "Introducer";
            client.ReconnectTimeoutMs      = (int)TimeSpan.FromSeconds(30).TotalMilliseconds;
            client.ErrorReconnectTimeoutMs = (int)TimeSpan.FromSeconds(30).TotalMilliseconds;
            client.ReconnectionHappened.Subscribe(async type =>
            {
                Log.Information($"Reconnection happened, type: {type}, url: {client.Url}");
                Log.Debug($"[Introducer] Connected: {type} {client.Url}");
                var command = $"update-role|interpreter|{GetLanIpAddress().MapToIPv4().ToString()}";
                Log.Debug($"[Introducer] Sending message: {command}");
                await client.Send(command);
            });
            client.DisconnectionHappened.Subscribe(type => {
                Log.Debug($"[Introducer] Disconnected, type {type}.");
            });

            client.MessageReceived.Subscribe(msg =>
            {
                Log.Debug($"[Introducer] Message received: {msg}");
            });

            client.Start().Wait();
        }
예제 #12
0
        static void Ping(dynamic Message, WebsocketClient Client)
        {
            Console.WriteLine("Got a ping");
            Ping ping = new Ping();

            Client.Send(JsonConvert.SerializeObject(ping));
        }
예제 #13
0
        static void OnCommand(dynamic Message, WebsocketClient Client)
        {
            Console.WriteLine("Got a command");
            string        data  = Message.data;
            List <string> argus = Library.stringParse(data);

            Console.WriteLine(argus);
            if (argus.Count == 3)
            {
                if (argus[2] == "uri")
                {
                    argus[1] = Library.PathToURI(argus[1]);
                }
            }
            string message = null;

            try
            {
                Process.Start(argus[0], argus[1]);
                message = "The Command Was Successful";
            }catch (Exception err)
            {
                message = $"The Command UnSuccessful \n {err}";
            }
            Message msg = new Message {
                message = message, from = "shell"
            };

            Client.Send(JsonConvert.SerializeObject(msg));
        }
 public void ConnectforStockQuote(string feedtoken, string clientcode)
 {
     try
     {
         //ServicePointManager.SecurityProtocol = (SecurityProtocolType)48 | (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072;
         if (feedtoken != "" && clientcode != "")
         {
             string ConnectionMsg = "{\"task\":\"cn\",\"channel\":\"\",\"token\":\"" + feedtoken + "\",\"user\": \"" + clientcode + "\",\"acctid\":\"" + clientcode + "\"}";
             var    url           = new Uri(_url2);
             _ws = new WebsocketClient(url);
             _ws.MessageReceived.Subscribe(msg => Receive2(msg.Text));
             _ws.Start();
             _ws.Send(ConnectionMsg);
             int i = 0;
             do
             {
                 HeartBeat(feedtoken, clientcode);
                 Thread.Sleep(60);
                 i++;
             } while (i < 10);
         }
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
예제 #15
0
        static async Task Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            var exitEvent = new ManualResetEvent(false);
            var url       = new Uri("wss://echo.websocket.org");
            var loop      = 1;

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

                client.MessageReceived.Subscribe(async msg =>
                {
                    Console.WriteLine($"Message received: {msg}");
                    await SendMessage(client, loop);
                    loop++;
                });

                await client.Start();

                await Task.Run(() => client.Send($"sawasdee first time"));

                exitEvent.WaitOne();
            }
        }
예제 #16
0
        public async Task SendBinaryMessage_ShouldWork()
        {
            using (IWebsocketClient client = new WebsocketClient(WebsocketUrl))
            {
                string received      = null;
                var    receivedEvent = new ManualResetEvent(false);

                client.MessageReceived.Subscribe(msg =>
                {
                    var msgText = msg.Text ?? string.Empty;
                    if (msgText.Contains("Unrecognized request"))
                    {
                        received = msgText;
                        receivedEvent.Set();
                    }
                });

                await client.Start();

                client.Send(new byte[] { 10, 14, 15, 16 });

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

                Assert.NotNull(received);
            }
        }
예제 #17
0
        public void SendMessage(Sensor sensor)
        {
            LoriotDTO msg = new LoriotDTO();

            msg.cmd       = "tx";
            msg.EUI       = sensor.sensorEUID;
            msg.data      = sensor.servoSetting;
            msg.port      = 3;
            msg.confirmed = false;
            clientWS.Send(JsonConvert.SerializeObject(msg));
            Console.WriteLine("Message sent");


            var log = new SensorLog();

            sensor = _context.Sensor.AsQueryable().First(s => s.sensorEUID == sensor.sensorEUID);

            log.servoSetting = sensor.servoSetting;
            log.timestamp    = DateTime.Now;

            log.sensorID = sensor.sensorID;

            slc.PostSensorLog(log).Wait();
            _context.SaveChanges();
        }
        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();
        }
예제 #19
0
        static void  Main(string[] args)
        {
            var url = new Uri("ws://localhost:9010");

            Directory.CreateDirectory(OUTPUT_FOLDER);

            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);
            });

            using (var ws = new WebsocketClient(url, factory))
            {
                ws.MessageReceived.Subscribe(msg => MessageParse(ws, msg));

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

                try
                {
                    ws.StartOrFail().Wait();
                }
                catch (Exception)
                {
                    Console.WriteLine("Failed to connect to LGHUB_agent, is Logitech G HUB running?");
                    Console.WriteLine("Press any key to quit.");
                    Console.ReadKey();
                    return;
                }

                Console.WriteLine("LGHUB_agent connected.");
                Console.WriteLine("");

                ws.Send(JsonConvert.SerializeObject(new
                {
                    msgId = "",
                    verb  = "GET",
                    path  = "/updates/info"
                }));

                startTime = DateTime.Now;

                while ((DateTime.Now - startTime).Milliseconds < 500)
                {
                    Thread.Sleep(100);
                }

                Console.WriteLine("");
                Console.WriteLine("Found all .xml files");
                Console.WriteLine("Press any key to quit.");
                Console.ReadKey();
            }
        }
예제 #20
0
        static void OnBulkRequest(dynamic Message, WebsocketClient Client)
        {
            string     time = Message.time;
            ClientBulk bulk = new ClientBulk {
                time = time
            };

            Client.Send(JsonConvert.SerializeObject(bulk));
        }
예제 #21
0
    private void SendWsMessage(string cmd, JsonMessageData data)
    {
        var msg = new JsonMessage {
            command = cmd, data = data
        };
        var msgStr = JsonUtility.ToJson(msg);

        ws.Send(msgStr);
    }
예제 #22
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

            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);

                var inputStream = $"{ input.type }";

                switch (inputStream)
                {
                case "quote": break;
                }
            });

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

            await client.Start();

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

            client.Send(ConversionManager.Serialize(query));
        }
예제 #23
0
        private static async Task StartSendingPing(WebsocketClient client)
        {
            while (true)
            {
                await Task.Delay(1000);

                await client.Send("ping");
            }
        }
 /// <summary>
 /// Send message to exchange.
 /// </summary>
 /// <param name="message">Byte message in proto format. <see cref="DigitexWire.Message"/></param>
 /// <returns></returns>
 public bool Send(byte[] message)
 {
     if (OrderSocket == null || !OrderSocket.IsRunning)
     {
         return(false);
     }
     OrderSocket.Send(message);
     return(true);
 }
 void SendPayload(Opcode op, JsonObject data)
 {
     using (MemoryStream ms = new MemoryStream()) {
         JSON.WriteNodeToStream(new JsonObject {
             ["op"] = new JsonValue(op),
             ["d"]  = data
         }, ms);
         socket.Send(ms.ToArray());
     }
 }
예제 #26
0
파일: Form1.cs 프로젝트: xzzpig/CloudText
 protected override void WndProc(ref Message m)
 {
     base.WndProc(ref m);
     Console.WriteLine(m);
     if (m.Msg == 0x31d && wsclient != null && Properties.Settings.Default.autoset == CheckState.Checked)
     {
         var req = new CloudTextPackage(0, null, null, "Set", Clipboard.GetText());
         wsclient.Send(JsonConvert.SerializeObject(req));
     }
 }
        public async Task Send(IWsMessage message, CancellationToken cancellationToken = default)
        {
            await EnsureSocketConnection();

            await Task.Run(() => _client.Send(JSerializer.Serialize(message)), cancellationToken);

            if (_configuration.ReconnectEnabled && _configuration.ResubscribeOnReconnect)
            {
                _subscriptions.Push(message);
            }
        }
        private Task Send(string message)
        {
            if (_options.debugMode)
            {
                Console.WriteLine(
                    $"***WebSocket outgoing message ({DateTime.Now.ToString(CultureInfo.CurrentCulture)}): ***" +
                    $"\n{JsonConvert.SerializeObject(JsonConvert.DeserializeObject(message), Formatting.Indented)}" +
                    "\n******");
            }

            return(Task.Run(() => _ws.Send(message)));
        }
예제 #29
0
        public override async Task LoadDevicesAsync()
        {
            if (_ws == null)
            {
                // Check if LGHUB_agent is back
                await InitialiseWS();
            }

            if (_ws == null)
            {
                // LGHUB_agent is not back
                return;
            }

            _ws.Send(JsonConvert.SerializeObject(new
            {
                msgId = "",
                verb  = "GET",
                path  = "/devices/list"
            }));
        }
예제 #30
0
파일: Form1.cs 프로젝트: xzzpig/CloudText
        private async void connectWs()
        {
            Console.WriteLine(Properties.Settings.Default.wsuri);
            var ws = new WebsocketClient(new Uri(Properties.Settings.Default.wsuri));

            _ = Task.Run(async() =>
            {
                await Task.Delay(1000);
                if (!ws.IsRunning)
                {
                    new ConfigForm("无法连接到websocket").ShowDialog();
                }
            });

            ws.MessageReceived.Subscribe(action => {
                var message = action.Text;
                Console.WriteLine(message);
                var response = JsonConvert.DeserializeObject <CloudTextPackage>(message);
                switch (response.action)
                {
                case "Auth":
                    if (response.data != "success")
                    {
                        new ConfigForm("账号登录失败").ShowDialog();
                    }
                    else
                    {
                        this.wsclient = ws;
                    }
                    break;

                case "Set":
                    var t = new Thread(() => {
                        try
                        {
                            if (Clipboard.GetText() != response.data && Properties.Settings.Default.autoget == CheckState.Checked)
                            {
                                Clipboard.SetText(response.data);
                            }
                        }
                        catch (Exception e) { }
                    });
                    t.SetApartmentState(ApartmentState.STA);
                    t.Start();
                    break;
                }
            });
            var req = new CloudTextPackage(0, Properties.Settings.Default.username, Properties.Settings.Default.password, "Auth", null);
            await ws.Start();

            await ws.Send(JsonConvert.SerializeObject(req));
        }