public async Task SendLargeBinaryMessage(bool useNinja)
        {
            using (var server = new Server())
            {
                server.StartListener();

                // Create client
                WebSocket webSocket;
                if (useNinja)
                {
                    var factory = new WebSocketClientFactory();
                    webSocket = await factory.ConnectAsync(server.Address, new WebSocketClientOptions(), CancellationToken.None);
                }
                else
                {
                    var clientWebSocket = new ClientWebSocket();
                    await clientWebSocket.ConnectAsync(server.Address, CancellationToken.None);
                    webSocket = clientWebSocket;
                }

                // Send large message
                byte[] message = new byte[10000];
                new Random().NextBytes(message);
                await SendBinaryMessage(webSocket, message, 1024);

                // Close
                await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Close", CancellationToken.None);

                Assert.Single(server.ReceivedMessages);
                Assert.Equal(message, server.ReceivedMessages[0]);
            }
        }
        public async Task Run()
        {
            var factory = new WebSocketClientFactory();
            var uri     = new Uri("ws://localhost:27416/chat");

            using (WebSocket webSocket = await factory.ConnectAsync(uri))
            {
                var pipe = new Pipe();
                // receive loop
                Task readTask = Receive(webSocket, pipe.Writer);
                Task reading  = ReadPipeAsync(webSocket, pipe.Reader);

                for (int i = 0; i < 10; i++)
                {
                    // send a message
                    await Send(webSocket);

                    Console.ReadLine();
                }

                // initiate the close handshake
                await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, null, CancellationToken.None);

                // wait for server to respond with a close frame
                await readTask;
            }
        }
        async Task <string> sendrcv(Uri webSocketUri, string expression)
        {
            var factory = new WebSocketClientFactory();

            using (WebSocket webSocket = await factory.ConnectAsync(webSocketUri))
            {
                try
                {
                    // receive loop
                    var readTask = Receive(webSocket);

                    // send a message
                    await Send(webSocket, expression);

                    // initiate the close handshake
                    await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, null, CancellationToken.None);

                    // wait for server to respond with a close frame
                    List <string> returnedData = await readTask;
                    return(String.Join("", returnedData));
                }
                catch (WebSocketException)
                {
                    return(null);
                }
            }
        }
Exemplo n.º 4
0
        /// <inheritdoc cref="ISocketAdapter.ConnectAsync"/>
        public async Task ConnectAsync(Uri uri, int timeout)
        {
            if (_webSocket != null && _webSocket.State == WebSocketState.Open)
            {
                // Already connected so we can return.
                return;
            }

            _cancellationSource = new CancellationTokenSource();
            _uri         = uri;
            IsConnecting = true;

            var clientFactory = new WebSocketClientFactory();

            try
            {
                var cts       = new CancellationTokenSource(TimeSpan.FromSeconds(timeout));
                var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(_cancellationSource.Token, cts.Token);
                _webSocket = await clientFactory.ConnectAsync(_uri, _options, linkedCts.Token).ConfigureAwait(false);

                _ = Task.Factory.StartNew(_ => ReceiveLoop(_webSocket, _cancellationSource.Token),
                                          TaskCreationOptions.LongRunning, _cancellationSource.Token);
                Connected?.Invoke();
                IsConnected = true;
            }
            catch (Exception)
            {
                IsConnected = false;
                throw;
            }
            finally
            {
                IsConnecting = false;
            }
        }
Exemplo n.º 5
0
        static async Task Main(string[] args)
        {
            if (args.Length < 6)
            {
                return;
            }

            POCViewModel vm         = null;
            var          rnd        = new Random(Guid.NewGuid().GetHashCode());
            var          clientName = ConfigData.Instance.ClientBaseName + rnd.Next();
            var          bbr        = new BoundingBoxRequest(name: clientName,
                                                             minLongitude: int.Parse(args[1]),
                                                             minLatitude: int.Parse(args[3]),
                                                             maxLongitude: int.Parse(args[2]),
                                                             maxLatitude: int.Parse(args[4]));

            var factory = new WebSocketClientFactory();
            var client  = factory.Create(ConfigData.Instance.Hostname, ConfigData.Instance.Port, ConfigData.Instance.ClientType);

            if (await client.InitializeAsync())
            {
                vm = new POCViewModel(client, clientName, bbr, args[0]);
                await vm.StartUpdatesListener();
            }

            await Task.Delay(int.Parse(args[5]));

            if (vm != null)
            {
                vm.Dispose();
            }

            Environment.Exit(0);
        }
Exemplo n.º 6
0
        public async void Connect(System.Uri uri)
        {
            var clientFactory = new WebSocketClientFactory();

            cancellation = new CancellationTokenSource();

            Connecting = true;

            try
            {
                using (WebSocket = await clientFactory.ConnectAsync(uri, ClientOptions, cancellation.Token))
                {
                    Connecting       = false;
                    ConnectionActive = true;
                    Connected?.Invoke();

                    await Receive(WebSocket, cancellation.Token);
                }
            }
            catch (System.ObjectDisposedException)
            {
                // client closed
                Debug.Log("closed connection");
            }
            catch (System.Exception ex)
            {
                Debug.LogError(ex);
                ReceivedError?.Invoke(ex);
            }
            finally
            {
                Disconnect();
            }
        }
Exemplo n.º 7
0
 internal ParseLiveQueryClient(Uri hostUri, WebSocketClientFactory webSocketClientFactory,
                               ISubscriptionFactory subscriptionFactory, ITaskQueue taskQueue)
 {
     _hostUri                 = hostUri;
     _applicationId           = ParseClient.CurrentConfiguration.ApplicationId;
     _webSocketClientFactory  = webSocketClientFactory;
     _webSocketClientCallback = new WebSocketClientCallback(this);
     _subscriptionFactory     = subscriptionFactory;
     _taskQueue               = taskQueue;
 }
 internal ParseLiveQueryClient(Uri hostUri, WebSocketClientFactory webSocketClientFactory,
                               ISubscriptionFactory subscriptionFactory, ITaskQueue taskQueue)
 {
     _hostUri                 = hostUri;
     _applicationId           = ParseClient.Instance.Services.ServerConnectionData.ApplicationID;
     _webSocketClientFactory  = webSocketClientFactory;
     _webSocketClientCallback = new WebSocketClientCallback(this);
     _subscriptionFactory     = subscriptionFactory;
     _taskQueue               = taskQueue;
 }
Exemplo n.º 9
0
        public async Task Connect(string ip)
        {
            if (client != null)
            {
                throw new Exception("Already connected to remote.");
            }

            var fac = new WebSocketClientFactory();

            client = await fac.ConnectAsync(new Uri(ip));
        }
Exemplo n.º 10
0
        public override async void DidFinishLaunching(NSNotification notification)
        {
            this.factory = new WebSocketClientFactory();
            var uri = new Uri("ws://127.0.0.1:8080");

            this.webSocket = await this.factory.ConnectAsync(uri);

            this.jsonRpc = new JsonRpc(new WebSocketMessageHandler(webSocket));
            this.jsonRpc.StartListening();
            var result = await jsonRpc.InvokeAsync <int>("Add", 5, 10);

            Console.WriteLine(result);
        }
Exemplo n.º 11
0
        public async void Connect(Uri uri)
        {
            // not if already started
            if (webSocket != null)
            {
                // paul:  exceptions are better than silence
                ReceivedError?.Invoke(new Exception("Client already connected"));
                return;
            }

            this.uri = uri;
            // We are connecting from now until Connect succeeds or fails
            Connecting = true;

            var options = new WebSocketClientOptions()
            {
                NoDelay              = true,
                KeepAliveInterval    = TimeSpan.Zero,
                SecWebSocketProtocol = "binary"
            };

            cancellation = new CancellationTokenSource();

            var clientFactory = new WebSocketClientFactory();

            try
            {
                using (webSocket = await clientFactory.ConnectAsync(uri, options, cancellation.Token))
                {
                    var token = cancellation.Token;
                    IsConnected = true;
                    Connecting  = false;
                    Connected?.Invoke();

                    await ReceiveLoop(webSocket, token);
                }
            }
            catch (ObjectDisposedException)
            {
                // No error, the client got closed
            }
            catch (Exception ex)
            {
                ReceivedError?.Invoke(ex);
            }
            finally
            {
                Disconnect();
                Disconnected?.Invoke();
            }
        }
        public async Task SendLargeBinaryMessage(bool useNinja)
        {
            using (var server = new Server())
            {
                server.StartListener();

                // Create client
                WebSocket webSocket;
                if (useNinja)
                {
                    var factory = new WebSocketClientFactory();
                    webSocket = await factory.ConnectAsync(server.Address, new WebSocketClientOptions(), CancellationToken.None);
                }
                else
                {
                    var clientWebSocket = new ClientWebSocket();
                    await clientWebSocket.ConnectAsync(server.Address, CancellationToken.None);

                    webSocket = clientWebSocket;
                }

                // Send large message
                byte[] message = new byte[10000];
                new Random().NextBytes(message);
                await SendBinaryMessage(webSocket, message, 1024);

                // Close
                await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Close", CancellationToken.None);

                // Wait for the server to receive our close message
                var stopwatch = Stopwatch.StartNew();
                while (server.State == WebSocketState.Open)
                {
                    await Task.Delay(5);

                    if (stopwatch.Elapsed.TotalSeconds > 10)
                    {
                        throw new TimeoutException("Timeout expired after waiting for close handshake to complete");
                    }
                }

                Assert.Single(server.ReceivedMessages);
                Assert.Equal(message, server.ReceivedMessages[0]);
            }
        }
Exemplo n.º 13
0
        /// <inheritdoc cref="ISocketAdapter.Connect"/>
        public async void Connect(Uri uri, int timeout)
        {
            if (_webSocket != null)
            {
                ReceivedError?.Invoke(new SocketException((int)SocketError.IsConnected));
                return;
            }

            _cancellationSource = new CancellationTokenSource();
            _uri         = uri;
            IsConnecting = true;

            var clientFactory = new WebSocketClientFactory();

            try
            {
                var cts  = new CancellationTokenSource(TimeSpan.FromSeconds(timeout));
                var lcts = CancellationTokenSource.CreateLinkedTokenSource(_cancellationSource.Token, cts.Token);
                using (_webSocket = await clientFactory.ConnectAsync(_uri, _options, lcts.Token))
                {
                    IsConnected  = true;
                    IsConnecting = false;
                    Connected?.Invoke();

                    await ReceiveLoop(_webSocket, _cancellationSource.Token);
                }
            }
            catch (TaskCanceledException)
            {
                // No error, the socket got closed via the cancellation signal.
            }
            catch (ObjectDisposedException)
            {
                // No error, the socket got closed.
            }
            catch (Exception e)
            {
                ReceivedError?.Invoke(e);
            }
            finally
            {
                Close();
                Closed?.Invoke();
            }
        }
        public override SocketTasks StartClient()
        {
            string conUrl = Url;

            if (conUrl.EndsWith("/"))
            {
                conUrl = conUrl.Substring(0, conUrl.Length - 1);
            }

            conUrl += "/mlapi-connection";

            client = WebSocketClientFactory.Create(conUrl);

            client.SetOnOpen(() =>
            {
                clientEventQueue.Enqueue(new ClientEvent()
                {
                    Type    = NetEventType.Connect,
                    Payload = new ArraySegment <byte>()
                });
            });

            client.SetOnClose((code) =>
            {
                clientEventQueue.Enqueue(new ClientEvent()
                {
                    Type    = NetEventType.Disconnect,
                    Payload = new ArraySegment <byte>()
                });
            });

            client.SetOnPayload((payload) =>
            {
                clientEventQueue.Enqueue(new ClientEvent()
                {
                    Type    = NetEventType.Disconnect,
                    Payload = payload
                });
            });

            client.Connect();

            return(SocketTask.Done.AsTasks());
        }
Exemplo n.º 15
0
        public async Task Run()
        {
            var factory = new WebSocketClientFactory();

            using (WebSocket webSocket = await factory.ConnectAsync(new Uri("ws://localhost:27416/chat")))
            {
                var readTask = Receive(webSocket);

                for (int i = 0; i < 10; i++)
                {
                    var writeBuffer = new ArraySegment <byte>(Encoding.UTF8.GetBytes($"Test{i}"));
                    await webSocket.SendAsync(writeBuffer, WebSocketMessageType.Text, true, CancellationToken.None);
                }

                await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, null, CancellationToken.None);

                await readTask;
            }
        }
Exemplo n.º 16
0
        public async Task Run()
        {
            var factory = new WebSocketClientFactory();
            WebSocketClientOptions options = new WebSocketClientOptions()
            {
                NoDelay = true, KeepAliveInterval = TimeSpan.Zero
            };

            using (_webSocket = await factory.ConnectAsync(_uri, options))
            {
                var source = new CancellationTokenSource();
                _token = source.Token;

                Random rand = new Random(_seed);
                _expectedValues = new byte[50][];
                for (int i = 0; i < _expectedValues.Length; i++)
                {
                    int    numBytes = rand.Next(_minNumBytesPerMessage, _maxNumBytesPerMessage);
                    byte[] bytes    = new byte[numBytes];
                    rand.NextBytes(bytes);
                    _expectedValues[i] = bytes;
                }

                Task   recTask    = Task.Run(ReceiveLoop);
                byte[] sendBuffer = new byte[_maxNumBytesPerMessage];
                for (int i = 0; i < _numItems; i++)
                {
                    int    index = i % _expectedValues.Length;
                    byte[] bytes = _expectedValues[index];
                    Buffer.BlockCopy(bytes, 0, sendBuffer, 0, bytes.Length);
                    ArraySegment <byte> buffer = new ArraySegment <byte>(sendBuffer, 0, bytes.Length);
                    await _webSocket.SendAsync(buffer, WebSocketMessageType.Binary, true, source.Token);
                }

                await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "So long and thanks for all the bits", source.Token);

                recTask.Wait();
            }
        }
Exemplo n.º 17
0
        public override async Task <IConnection> ConnectAsync(Uri uri)
        {
            var options = new WebSocketClientOptions
            {
                NoDelay              = true,
                KeepAliveInterval    = TimeSpan.Zero,
                SecWebSocketProtocol = "binary"
            };

            if (uri.IsDefaultPort)
            {
                var builder = new UriBuilder(uri)
                {
                    Port = Port
                };
                uri = builder.Uri;
            }

            var       clientFactory = new WebSocketClientFactory();
            WebSocket webSocket     = await clientFactory.ConnectAsync(uri, options);

            return(new WebsocketConnection(webSocket));
        }
    /// <summary>
    ///     Connect to Home Assistant
    /// </summary>
    /// <param name="host">The host name</param>
    /// <param name="port">Network port</param>
    /// <param name="ssl">Set true to use ssl</param>
    /// <param name="token">The access token to use</param>
    /// <param name="websocketPath">The relative websocket path to use connecting</param>
    /// <param name="cancelToken">Cancellation token</param>
    public static async Task <IHomeAssistantConnection> ConnectClientAsync(string host, int port, bool ssl, string token,
                                                                           string websocketPath,
                                                                           CancellationToken cancelToken)
    {
        var loggerFactory = LoggerFactory.Create(b => b.AddConsole());
        var loggerConnect = loggerFactory.CreateLogger <IHomeAssistantConnection>();
        var loggerClient  = loggerFactory.CreateLogger <IHomeAssistantClient>();
        var loggerResultMessageHandler = loggerFactory.CreateLogger <ResultMessageHandler>();
        var settings = new HomeAssistantSettings
        {
            Host  = host,
            Port  = port,
            Ssl   = ssl,
            Token = token
        };
        var optionsSettings        = Options.Create(settings);
        var apiManager             = new HomeAssistantApiManager(optionsSettings, new HttpClient());
        var connectionFactory      = new HomeAssistantConnectionFactory(loggerConnect, apiManager);
        var pipeLineFactory        = new WebSocketClientTransportPipelineFactory();
        var websocketClientFactory = new WebSocketClientFactory(Options.Create(settings));
        var client = new HomeAssistantClient(loggerClient, websocketClientFactory, pipeLineFactory, connectionFactory);

        return(await client.ConnectAsync(host, port, ssl, token, websocketPath, cancelToken).ConfigureAwait(false));
    }
Exemplo n.º 19
0
        static async Task RunClient()
        {
            var factory = new WebSocketClientFactory();
            var uri     = new Uri("ws://localhost:27416/chat");

            using (WebSocket webSocket = await factory.ConnectAsync(uri))
            {
                var jsonRpc = new JsonRpc(new WebSocketMessageHandler(webSocket));
                jsonRpc.StartListening();

                EntityServiceResult result = await CampaginServiceGetCountRequest.MakeCall(jsonRpc);

                Console.WriteLine(result.Result.ToString());

                result = await CampaginServiceGetEntityRequest.MakeCall(jsonRpc, 0, 200, 1, "CampaignName");

                Console.WriteLine(result.Result.ToString());

                Console.ReadLine();

                // initiate the close handshake
                await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, null, CancellationToken.None);
            }
        }
        const int BUFFER_SIZE = 1 * 1024 * 1024 * 1024; // 1GB

        public async Task Run()
        {
            var factory = new WebSocketClientFactory();
            var uri     = new Uri("ws://localhost:27416/chat");
            var options = new WebSocketClientOptions()
            {
                KeepAliveInterval = TimeSpan.FromMilliseconds(500)
            };

            using (WebSocket webSocket = await factory.ConnectAsync(uri, options))
            {
                // receive loop
                Task readTask = Receive(webSocket);

                // send a message
                await Send(webSocket);

                // initiate the close handshake
                await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, null, CancellationToken.None);

                // wait for server to respond with a close frame
                await readTask;
            }
        }
 public ParseLiveQueryClient(WebSocketClientFactory webSocketClientFactory) : this(GetDefaultUri(), webSocketClientFactory)
 {
 }
 public ParseLiveQueryClient(Uri hostUri, WebSocketClientFactory webSocketClientFactory) :
     this(hostUri, webSocketClientFactory, new SubscriptionFactory(), new TaskQueueWrapper())
 {
 }