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;
            }
        }
        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]);
            }
        }
        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);
                }
            }
        }
예제 #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;
            }
        }
예제 #5
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();
            }
        }
예제 #6
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));
        }
예제 #7
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]);
            }
        }
        /// <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();
            }
        }
예제 #10
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;
            }
        }
예제 #11
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();
            }
        }
예제 #12
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));
        }
        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;
            }
        }
예제 #14
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);
            }
        }