ConnectAsync() public method

public ConnectAsync ( System uri, System cancellationToken ) : System.Threading.Tasks.Task
uri System
cancellationToken System
return System.Threading.Tasks.Task
Exemplo n.º 1
5
        private void TestWebSockets()
        {
            var socket = new ClientWebSocket();
            Console.WriteLine("Connecting");
            socket.ConnectAsync(new Uri("wss://echo.websocket.org"), CancellationToken.None).Wait();

            Console.WriteLine("Sending");
            socket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes("Hello")), WebSocketMessageType.Text, true, CancellationToken.None).Wait();

            var buffer = new byte[1024];
            Console.WriteLine("Receiving");
            var result = socket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None).Result;

            Console.WriteLine($"Recieved: {Encoding.UTF8.GetString(buffer, 0, result.Count)}");
        }
        public async Task ConnectAsync(Uri uri, WebSocketConnectionOptions options)
        {
            if (_ws != null)
            {
                _ws.Dispose();
            }

            //ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, errors) =>
            //{
            //    //// local dev, just approve all certs
            //    //if (development) return true;
            //    //return errors == SslPolicyErrors.None;
            //    return true;
            //};
            _ws = CreateClient();
            //var cert = new X509Certificate2(@"C:\Users\41608\Downloads\cert\client1-crt.pem");
            //var privateKey = cert.PrivateKey as RSACryptoServiceProvider;
            //privateKey.en
            //_ws.Options.ClientCertificates.Add(cert);
            _connectionToken = new CancellationTokenSource();
            await _ws.ConnectAsync(uri, _connectionToken.Token);

            await Task.Factory.StartNew(ListenAsync, _connectionToken.Token);

            await Task.Factory.StartNew(ListenStateAsync, _connectionToken.Token);
        }
		public void BasicRoundTrip()
		{
			var serializer = new JsonCommonSerializer();

			var port = new Random().Next(6000, 60000);

			var options = new WebSocketListenerOptions();
			options.SubProtocols = new[] { "SignalR" };
			var listener = new WebSocketListener(new IPEndPoint(IPAddress.Loopback, port), options);
			var rfc6455 = new vtortola.WebSockets.Rfc6455.WebSocketFactoryRfc6455(listener);
			listener.Standards.RegisterStandard(rfc6455);
			var serverTransport = listener.GenerateTransportSource();
			var serverRouter = new DefaultMessageRouter(serverTransport, serializer);
			serverRouter.AddService<IMyService>(new MyService());
			listener.Start();

			var client = new ClientWebSocket();
			client.Options.AddSubProtocol("SignalR");
			var clientTransport = client.GenerateTransportSource();
			var clientRouter = new DefaultMessageRouter(clientTransport, serializer);
			var proxy = clientRouter.AddInterface<IMyService>();
			client.ConnectAsync(new Uri("ws://localhost:" + port + "/"), CancellationToken.None).Wait();

			var result = proxy.Add(3, 4).Result;
			Assert.Equal(7, result);

			clientRouter.Dispose();
			clientTransport.Dispose();
			client.Dispose();

			serverRouter.Dispose();
			serverTransport.Dispose();
			listener.Dispose();
		}
Exemplo n.º 4
0
        public virtual Stream Connect(Uri uri, bool requireAuthentication) {
            // IIS starts python.exe processes lazily on the first incoming request, and will terminate them after a period
            // of inactivity, making it impossible to attach. So before trying to connect to the debugger, "ping" the website
            // via HTTP to ensure that we have something to connect to.
            try {
                var httpRequest = WebRequest.Create(new UriBuilder(uri) { Scheme = "http", Port = -1, Path = "/" }.Uri);
                httpRequest.Method = WebRequestMethods.Http.Head;
                httpRequest.Timeout = 5000;
                httpRequest.GetResponse().Dispose();
            } catch (WebException) {
                // If it fails or times out, just go ahead and try to connect anyway, and rely on normal error reporting path.
            }

            var webSocket = new ClientWebSocket();
            try {
                webSocket.ConnectAsync(uri, CancellationToken.None).GetAwaiter().GetResult();
                var stream = new WebSocketStream(webSocket, ownsSocket: true);
                webSocket = null;
                return stream;
            } catch (WebSocketException ex) {
                throw new ConnectionException(ConnErrorMessages.RemoteNetworkError, ex);
            } catch (IOException ex) {
                throw new ConnectionException(ConnErrorMessages.RemoteNetworkError, ex);
            } catch (PlatformNotSupportedException ex) {
                throw new ConnectionException(ConnErrorMessages.RemoteUnsupportedTransport, ex);
            } finally {
                if (webSocket != null) {
                    webSocket.Dispose();
                }
            }
        }
        public async void ConnectAndStartReceivingToWebSocket()
        {
            ClientWebSocket webSocket = null;
            var uncontext = new Uri(_wsLiteratureUncontextCom);

            try
            {
                webSocket = new ClientWebSocket();
                await webSocket.ConnectAsync(uncontext, CancellationToken.None);
                await Receive(webSocket);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: {0}", ex);
            }
            finally
            {
                if (webSocket != null)
                {
                    webSocket.Dispose();
                    UncontextedData.OnCompleted();
                }
                Console.WriteLine("Closed websocket.");
            }
        }
Exemplo n.º 6
0
        public async Task WebsocketBasic(HostType hostType)
        {
            using (ApplicationDeployer deployer = new ApplicationDeployer())
            {
                string applicationUrl = deployer.Deploy(hostType, WebsocketBasicConfiguration);

                using (var client = new ClientWebSocket())
                {
                    await client.ConnectAsync(new Uri(applicationUrl.Replace("http://", "ws://")), CancellationToken.None);

                    var receiveBody = new byte[100];

                    for (int i = 0; i < 4; i++)
                    {
                        var message = "Message " + i.ToString();
                        byte[] sendBody = Encoding.UTF8.GetBytes(message);
                        await client.SendAsync(new ArraySegment<byte>(sendBody), WebSocketMessageType.Text, true, CancellationToken.None);
                        var receiveResult = await client.ReceiveAsync(new ArraySegment<byte>(receiveBody), CancellationToken.None);

                        Assert.Equal(WebSocketMessageType.Text, receiveResult.MessageType);
                        Assert.True(receiveResult.EndOfMessage);
                        Assert.Equal(sendBody.Length, receiveResult.Count);
                        Assert.Equal(message, Encoding.UTF8.GetString(receiveBody, 0, receiveResult.Count));
                    }
                }
            }
        }
		public void BasicRoundTrip()
		{
			var serializer = new JsonCommonSerializer();

			var server = new HttpListener();
			server.Prefixes.Add("http://localhost:20000/");
			server.Start();
			var serverTransport = server.GenerateTransportSource();
			var serverRouter = new DefaultMessageRouter(serverTransport, serializer);
			serverRouter.AddService<IMyService>(new MyService());

			var client = new ClientWebSocket();
			client.Options.SetBuffer(8192, 8192);
			var clientTransport = client.GenerateTransportSource();
			var clientRouter = new DefaultMessageRouter(clientTransport, serializer);
			var proxy = clientRouter.AddInterface<IMyService>();

			client.ConnectAsync(new Uri("ws://localhost:20000/"), CancellationToken.None).Wait();

			var result = proxy.Add(3, 4).Result;
			Assert.Equal(7, result);

			clientRouter.Dispose();
			clientTransport.Dispose();
			client.Dispose();

			serverRouter.Dispose();
			serverTransport.Dispose();
			server.Stop();
			server.Close();
		}
        /// <summary>
        ///
        /// </summary>
        /// <param name="uri"></param>
        /// <param name="options"></param>
        /// <exception cref="TimeoutException"></exception>
        /// <exception cref="WebSocketException"></exception>
        /// <returns></returns>
        public async Task ConnectAsync(Uri uri)
        {
            //#if NET45

            //#elif NETSTANDARD2_0
            //#endif
            //if (_io.Options.Proxy != null)
            //{
            //    _ws.Options.Proxy = _io.Options.Proxy;
            //}
            if (_ws != null)
            {
                _ws.Dispose();
            }
            _ws                = new System.Net.WebSockets.ClientWebSocket();
            Options            = _ws.Options;
            _wsWorkTokenSource = new CancellationTokenSource();
            var wsConnectionTokenSource = new CancellationTokenSource(_io.Options.ConnectionTimeout);

            try
            {
                await _ws.ConnectAsync(uri, wsConnectionTokenSource.Token);

                await Task.Factory.StartNew(ListenAsync);

                await Task.Factory.StartNew(ListenStateAsync);
            }
            catch (TaskCanceledException)
            {
                throw new TimeoutException();
            }
        }
Exemplo n.º 9
0
        public static async Task RunSample()
        {
            ClientWebSocket websocket = new ClientWebSocket();

            string url = "ws://localhost:7000/";
            Console.WriteLine("Connecting to: " + url);
            await websocket.ConnectAsync(new Uri(url), CancellationToken.None);

            int seed = 20000;
            Task[] taskList = new Task[seed];

            Stopwatch sw = new Stopwatch();
            sw.Restart();
            for (var i = 0; i < seed; i++)
            {
                //taskList[i] = Send(websocket);
                await Send(websocket);
            }

            //Task.WaitAll(taskList);
            sw.Stop();
            Console.WriteLine("seed:{0}, time:{1}", seed, sw.ElapsedMilliseconds);

            //if (result.CloseStatus.HasValue)
            //{
            //    Console.WriteLine("Closed; Status: " + result.CloseStatus + ", " + result.CloseStatusDescription);
            //}
            //else
            //{
            //    Console.WriteLine("Received message: " + Encoding.UTF8.GetString(incomingData, 0, result.Count));
            //}
        }
Exemplo n.º 10
0
        internal async Task<IAsyncTransport> ConnectAsync(Address address, Action<ClientWebSocketOptions> options)
        {
            Uri uri = new UriBuilder()
            {
                Scheme = address.Scheme,
                Port = GetDefaultPort(address.Scheme, address.Port),
                Host = address.Host,
                Path = address.Path
            }.Uri;

            ClientWebSocket cws = new ClientWebSocket();
            cws.Options.AddSubProtocol(WebSocketSubProtocol);
            if (options != null)
            {
                options(cws.Options);
            }

            await cws.ConnectAsync(uri, CancellationToken.None);
            if (cws.SubProtocol != WebSocketSubProtocol)
            {
                cws.Abort();

                throw new NotSupportedException(
                    string.Format(
                        CultureInfo.InvariantCulture,
                        "WebSocket SubProtocol used by the host is not the same that was requested: {0}",
                        cws.SubProtocol ?? "<null>"));
            }

            this.webSocket = cws;

            return this;
        }
Exemplo n.º 11
0
        public async void TestConnectWebSocket()
        {
            if (TestHelper.IsMono)
            {
                Assert.Inconclusive("Mono doesn't have support to WebSockets");
            }

            Assert.IsNotNull(WebServer.Module<WebSocketsModule>(), "WebServer has WebSocketsModule");

            Assert.AreEqual(WebServer.Module<WebSocketsModule>().Handlers.Count, 1, "WebSocketModule has one handler");

            var clientSocket = new ClientWebSocket();
            var ct = new CancellationTokenSource();
            await clientSocket.ConnectAsync(new Uri(Resources.WsServerAddress + "/test"), ct.Token);

            Assert.AreEqual(clientSocket.State, WebSocketState.Open, "Connection is open");

            var message = new ArraySegment<byte>(System.Text.Encoding.Default.GetBytes("HOLA"));
            var buffer = new ArraySegment<byte>(new byte[1024]);

            await clientSocket.SendAsync(message, WebSocketMessageType.Text, true, ct.Token);
            var result = await clientSocket.ReceiveAsync(buffer, ct.Token);

            Assert.IsTrue(result.EndOfMessage);
            Assert.IsTrue(System.Text.Encoding.UTF8.GetString(buffer.Array).TrimEnd((char) 0) == "WELCOME");
        }
        public static async Task RunSample()
        {
            ClientWebSocket websocket = new ClientWebSocket();

            string url = "ws://localhost:5000/";
            Console.WriteLine("Connecting to: " + url);
            await websocket.ConnectAsync(new Uri(url), CancellationToken.None);

            string message = "Hello World";
            Console.WriteLine("Sending message: " + message);
            byte[] messageBytes = Encoding.UTF8.GetBytes(message);
            await websocket.SendAsync(new ArraySegment<byte>(messageBytes), WebSocketMessageType.Text, true, CancellationToken.None);

            byte[] incomingData = new byte[1024];
            WebSocketReceiveResult result = await websocket.ReceiveAsync(new ArraySegment<byte>(incomingData), CancellationToken.None);

            if (result.CloseStatus.HasValue)
            {
                Console.WriteLine("Closed; Status: " + result.CloseStatus + ", " + result.CloseStatusDescription);
            }
            else
            {
                Console.WriteLine("Received message: " + Encoding.UTF8.GetString(incomingData, 0, result.Count));
            }
        }
Exemplo n.º 13
0
        public static async Task Connect(string uri)
        {
            ClientWebSocket webSocket = null;

            try
            {
                webSocket = new ClientWebSocket();
                await webSocket.ConnectAsync(new Uri(uri), CancellationToken.None);
                await Task.WhenAll(Receive(webSocket), Send(webSocket));
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: {0}", ex);
            }
            finally
            {
                if (webSocket != null)
                    webSocket.Dispose();
                Console.WriteLine();

                lock (consoleLock)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("WebSocket closed.");
                    Console.ResetColor();
                }
            }
        }
Exemplo n.º 14
0
        public async Task ListenAsync()
        {
            var socket = new ClientWebSocket();
            await socket.ConnectAsync(new Uri(ServerUrl.Replace("http://", "ws://")), CancellationToken.None);

            // listen for updates
            await Receive(socket);
        }
Exemplo n.º 15
0
		public void ConnectPusher()
		{
			_ws = new ClientWebSocket();
			_ws.ConnectAsync(new Uri("wss://ws.pusherapp.com/app/de504dc5763aeef9ff52?client=PC-Orbit&version=1.0&protocol=7"), _source.Token).Wait();
			
			_connected = true;

			ThreadingHelper.Thread(OnReceive).Launch();
		}
Exemplo n.º 16
0
    protected override void Main()
    {
      if (Environment.OSVersion.Version < new Version(6, 2))
      {
        TraceError(Text.LabRequiresWindows8OrHigher);
        return;
      }

      const int port = 5494;
      string subProtocol = GetType().Name;

      var userMessages = new BehaviorSubject<string>(null);

      var client = new ClientWebSocket();

      client.Options.AddSubProtocol(subProtocol);

      using (client)
      using (var cancel = new CancellationDisposable())
      using (ObservableHttpListener
        .StartWebSockets(new IPEndPoint(IPAddress.Loopback, port), subProtocol)
        .Subscribe(
          async request =>
          {
            using (var socket = request.WebSocket)
            {
              try
              {
                var message = await ReceiveMessageAsync(socket, cancel.Token);
                await SendMessageAsync("You sent \"" + message + "\"", socket, cancel.Token);
                await ReceiveCloseMessageAsync(socket, cancel.Token);
              }
              catch (OperationCanceledException)
              {
              }
            }
          },
          TraceError))
      using ((from _ in client.ConnectAsync(new Uri("ws://localhost:" + port), cancel.Token).ToObservable()
                .Do(_ => TraceLine(Environment.NewLine + "(Connected to host on sub-protocol \"{0}\")", client.SubProtocol))
              from message in userMessages.Where(m => m != null).Take(1)
              from __ in SendMessageAsync(message, client, cancel.Token).ToObservable()
              from response in ReceiveMessageAsync(client, cancel.Token).ToObservable()
                .Do(___ => client.CloseAsync(WebSocketCloseStatus.NormalClosure, "Done", cancel.Token))
              select response)
              .Subscribe(
                response => TraceLine("Response: {0}", response),
                TraceError,
                () => TraceLine("{0}: {1}", Text.Client, Text.Done)))
      {
        userMessages.OnNext(UserInput("{0}> ", Instructions.EnterAMessage));

        TraceStatus(Instructions.PressAnyKeyToCancel);

        WaitForKey();
      }
    }
Exemplo n.º 17
0
 public async Task Connect(string host, CancellationToken cancelToken)
 {
     _webSocket = new WebSocketClient();
     _webSocket.Options.Proxy = null;
     _webSocket.Options.SetRequestHeader("User-Agent", _config.UserAgent);
     _webSocket.Options.KeepAliveInterval = TimeSpan.Zero;
     _tempTask = await _webSocket.ConnectAsync(new Uri(host), cancelToken)//.ConfigureAwait(false);
         .ContinueWith(t => ReceiveAsync(cancelToken)).ConfigureAwait(false); 
     //TODO: ContinueWith is a temporary hack, may be a bug related to https://github.com/dotnet/corefx/issues/4429
 }
Exemplo n.º 18
0
        public async Task ConnectAsync(Uri uri, WebSocketConnectionOptions options)
        {
            _ws = new System.Net.WebSockets.ClientWebSocket();
            _connectionToken = new CancellationTokenSource();
            await _ws.ConnectAsync(uri, _connectionToken.Token);

            await Task.Factory.StartNew(ListenAsync, _connectionToken.Token);

            await Task.Factory.StartNew(ListenStateAsync, _connectionToken.Token);
        }
Exemplo n.º 19
0
        private static async Task startRunner()
        {
            var socketUrl = await getSocketUrl();
            ClientWebSocket ws = new ClientWebSocket();
            await ws.ConnectAsync(new Uri($"ws://{socketUrl}"), CancellationToken.None);
            var buffer = new byte[1024 * 10];
            await send(ws, new CreateNewGameRequestSocketMessage() { GameType = "sevens" });

            while (true)
            {
                var segment = new ArraySegment<byte>(buffer);

                var result = await ws.ReceiveAsync(segment, CancellationToken.None);

                switch (result.MessageType)
                {
                    case WebSocketMessageType.Binary:

                        byte[] bytes = new byte[result.Count];
                        Array.ConstrainedCopy(segment.Array, 0, bytes, 0, result.Count);
                        var obj = Serializer.Deserialize(bytes);
                        if (obj is GameStartedSocketMessage)
                        {
                            totalGames++;
                            games++;
                        }
                        else if (obj is AskQuestionSocketMessage)
                        {
                            var answerQ = (AskQuestionSocketMessage)obj;
                            await send(ws, new AnswerQuestionSocketMessage()
                            {
                                AnswerIndex = (short)(answerQ.Answers.Length > 1 ? 1 : 0)
                            });
                            totalAnswers++;
                        }
                        else if (obj is GameOverSocketMessage)
                        {
                            await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "Done", CancellationToken.None);
                            games--;
                            return;
                        }

                        break;
                    case WebSocketMessageType.Close:
                        await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "Done", CancellationToken.None);
                        break;
                    default:
                        throw new ArgumentOutOfRangeException();
                }


            }

        }
Exemplo n.º 20
0
        public async Task Connect(string host, CancellationToken cancelToken)
        {
            _webSocket = new WebSocketClient();
            _webSocket.Options.Proxy = null;
            _webSocket.Options.SetRequestHeader("User-Agent", _config.UserAgent);
            _webSocket.Options.KeepAliveInterval = TimeSpan.Zero;
            _tempTask = await _webSocket.ConnectAsync(new Uri(host), cancelToken)//.ConfigureAwait(false);
                        .ContinueWith(t => ReceiveAsync(cancelToken)).ConfigureAwait(false);

            //TODO: ContinueWith is a temporary hack, may be a bug related to https://github.com/dotnet/corefx/issues/4429
        }
Exemplo n.º 21
0
 private async Task<WebSocket> ConnectAsync(string address, string agent)
 {
     if (string.Equals(agent, "NativeWebSockets"))
     {
         var client = new ClientWebSocket();
         await client.ConnectAsync(new Uri(address), CancellationToken.None);
         return client;
     }
     else
     {
         // TODO: BUG: Require ws or wss schemes
         var client = new WebSocketClient();
         return await client.ConnectAsync(new Uri(address), CancellationToken.None);
     }
 }
        /// <summary>
        /// <c>overrideOnOk</c> will be called before the regular onOk has been processed, allowing customization of what happens
        /// on that response. Implement this method in a partial class to enable this behavior
        /// </summary>
        /// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param>
        /// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.ContainerInstance.Models.Api20210901.IContainerExecResponse"
        /// /> from the remote call</param>
        /// <param name="returnNow">/// Determines if the rest of the onOk method should be processed, or if the method should return
        /// immediately (set to true to skip further processing )</param>
        partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task <Microsoft.Azure.PowerShell.Cmdlets.ContainerInstance.Models.Api20210901.IContainerExecResponse> response, ref global::System.Threading.Tasks.Task <bool> returnNow)
        {
            var containerExecResponse = response.ConfigureAwait(false).GetAwaiter().GetResult();

            socket = new System.Net.WebSockets.ClientWebSocket();
            // Connect websocket
            socket.ConnectAsync(new System.Uri(containerExecResponse.WebSocketUri), _cancellationTokenSource.Token).ConfigureAwait(false).GetAwaiter().GetResult();
            socket.SendAsync(new ArraySegment <byte>(Encoding.UTF8.GetBytes(containerExecResponse.Password)), WebSocketMessageType.Text, true, _cancellationTokenSource.Token).ConfigureAwait(false).GetAwaiter().GetResult();

            var receiver = PullResponse();
            var sender   = PushCommand();

            Task.WaitAll(sender, receiver);
            returnNow = global::System.Threading.Tasks.Task.FromResult(true);
        }
Exemplo n.º 23
0
        private async Task PerformConnect(bool reconnecting = false)
        {
            var url = reconnecting ? _connectionInfo.Connection.Url : _connectionInfo.Connection.Url + "connect";
            url += TransportHelper.GetReceiveQueryString(_connectionInfo.Connection, _connectionInfo.Data, "webSockets");
            var builder = new UriBuilder(url);
            builder.Scheme = builder.Scheme == "https" ? "wss" : "ws";

            Debug.WriteLine("WS: " + builder.Uri);

            var webSocket = new ClientWebSocket();
            _connectionInfo.Connection.PrepareRequest(new WebSocketWrapperRequest(webSocket));

            await webSocket.ConnectAsync(builder.Uri, _disconnectToken);
            await ProcessWebSocketRequestAsync(webSocket, _disconnectToken);
        }
Exemplo n.º 24
0
        private static async Task ConnectToWebSocket()
        {
            var settingsConfigurator = _serviceProvider.GetService<IConfigureOptions<ClientSettings>>();
            settingsConfigurator.Configure(_settings);
            ClientWebSocket client = new ClientWebSocket();
            var clientId = Guid.NewGuid();
            var uri = $"{_settings.SocketBaseHostAddress}?clientId=" + clientId;
            await client.ConnectAsync(new Uri(uri), CancellationToken.None);

            while (client.State == WebSocketState.Open)
            {
                var messageDispatcher = new ClientMessageDispatcher(_settings, client, clientId);
                await messageDispatcher.Listen();
            }
        }
Exemplo n.º 25
0
        public override async Task<WebSocket> CreateWebSocketAsync(Uri address, WebHeaderCollection headers, ICredentials credentials,
            WebSocketTransportSettings settings, TimeoutHelper timeoutHelper)
        {
            ClientWebSocket webSocket = new ClientWebSocket();
            webSocket.Options.Credentials = credentials;
            webSocket.Options.AddSubProtocol(settings.SubProtocol);
            webSocket.Options.KeepAliveInterval = settings.KeepAliveInterval;
            foreach (var headerObj in headers)
            {
                var header = headerObj as string;
                webSocket.Options.SetRequestHeader(header, headers[header]);
            }

            await webSocket.ConnectAsync(address, timeoutHelper.CancellationToken);
            return webSocket;
        }
 private static ClientWebSocket ConnectToWebsocket(ClientWebSocket client, string handle, Helpers.ContainerizerProcess process)
 {
     client = new ClientWebSocket();
     try
     {
         client.ConnectAsync(
             new Uri("ws://localhost:" + process.Port + "/api/containers/" + handle + "/run"),
             CancellationToken.None).GetAwaiter().GetResult();
     }
     catch (WebSocketException ex)
     {
         throw new Exception("Make sure to enable websockets following instructions in the README.",
             ex);
     }
     return client;
 }
Exemplo n.º 27
0
        public static async Task Run(Control control, Bitmap bitmap)
        {
            using (var webSocket = new ClientWebSocket())
            {
                var stream = new WebSocketStream(webSocket);

                await webSocket.ConnectAsync(new Uri("ws://localhost:5050/ws"), CancellationToken.None);

                await DispatchStartAsync(control, bitmap, stream);

                while (true)
                {
                    await DispatchDeltaAsync(control, bitmap, stream);
                }
            }
        }
Exemplo n.º 28
0
		public async Task ConnectAsync(string url)
		{
			await DisconnectAsync();

			_disconnectToken = new CancellationTokenSource();
			var cancelToken = _disconnectToken.Token;

			_webSocket = new ClientWebSocket();
			_webSocket.Options.KeepAliveInterval = TimeSpan.Zero;
			await _webSocket.ConnectAsync(new Uri(url), cancelToken);
			_host = url;

			if (_isDebug)
				RaiseOnDebugMessage(DebugMessageType.Connection, $"Connected.");

			OnConnect();

			_lastHeartbeat = DateTime.UtcNow;
			_task = Task.Factory.ContinueWhenAll(CreateTasks(), x =>
			{
				if (_isDebug)
					RaiseOnDebugMessage(DebugMessageType.Connection, $"Disconnected.");

				//Do not clean up until all tasks have ended
				OnDisconnect();

				_disconnectToken.Dispose();
				_disconnectToken = null;
				_wasDisconnectedUnexpected = false;

				//Clear send queue
				_heartbeatInterval = 0;
				_lastHeartbeat = DateTime.MinValue;
				_webSocket.Dispose();
				_webSocket = null;
				byte[] ignored;
				while (_sendQueue.TryDequeue(out ignored)) { }

				if (_isConnected)
				{
					_isConnected = false;
					RaiseDisconnected(_wasDisconnectedUnexpected);
				}

				_task = null;
			});
		}
Exemplo n.º 29
0
        public WebSocketNetworkClient(Uri uri) {
            // iisnode starts node.exe processes lazily on the first incoming request, and will terminate them after a period
            // of inactivity, making it impossible to attach. So before trying to connect to the debugger, "ping" the website
            // via HTTP to ensure that we have something to connect to.
            try {
                var httpRequest = WebRequest.Create(new UriBuilder(uri) { Scheme = "http", Port = -1, Path = "/" }.Uri);
                httpRequest.Method = WebRequestMethods.Http.Head;
                httpRequest.Timeout = 5000;
                httpRequest.GetResponse().Dispose();
            } catch (WebException) {
                // If it fails or times out, just go ahead and try to connect anyway, and rely on normal error reporting path.
            }

            _webSocket = new ClientWebSocket();
            _webSocket.ConnectAsync(uri, CancellationToken.None).GetAwaiter().GetResult();
            _stream = new WebSocketStream(_webSocket);
        }
Exemplo n.º 30
0
        private async Task ReadEventsAsync()
        {
            var socket = new ClientWebSocket();
            await socket.ConnectAsync(new Uri("ws://localhost:7070/events"), CancellationToken.None);

            while (true)
            {
                var buffer = new byte[1024];
                var segment = new ArraySegment<byte>(buffer);

                var result = await socket.ReceiveAsync(segment, CancellationToken.None);

                var data = Encoding.UTF8.GetString(segment.Array, 0, result.Count);

                Debug.WriteLine(data);
            }
        }
Exemplo n.º 31
0
        public void TestMethod1()
        {
            var total = 10000;
            var msg = "hello";
            var client = new ClientWebSocket();
            client.ConnectAsync(new Uri("ws://localhost:8889/ws.axd"), CancellationToken.None).Wait();
            client.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes(total.ToString())), WebSocketMessageType.Text, true, CancellationToken.None).Wait();
            client.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes(msg)), WebSocketMessageType.Text, true, CancellationToken.None).Wait();

            var w = new Stopwatch();
            w.Start();
            ReceiveMessages(client, msg, total).Wait();
            w.Stop();
            Trace.WriteLine(w.ElapsedMilliseconds);

            while (_counter < total) Thread.Sleep(10);
        }
Exemplo n.º 32
0
		private async Task Connect()
		{
			var nextEndPoint = _endpoints.Dequeue();
			_endpoints.Enqueue(nextEndPoint);

			_webSocket = new ClientWebSocket();
			await _webSocket.ConnectAsync(nextEndPoint, CancellationToken.None);
			Beam.Logger.Info($"Connected to endpoint {nextEndPoint}");
			_channelJoined = true;
			_cancellationToken = new CancellationToken();
			_receiveThread = new Thread(StartRecieving)
			{
				Name = $"Chat Receive Thread for {_channelId}"
			};

			_receiveThread.Start();
		}
Exemplo n.º 33
0
        public async Task ConnectAsync(Uri uri, WebSocketConnectionOptions options)
        {
            if (_ws != null)
            {
                _ws.Dispose();
            }
            _ws = new System.Net.WebSockets.ClientWebSocket();
            //var cert = new X509Certificate2(@"C:\Users\41608\Downloads\cert\client1-crt.pem");
            //var privateKey = cert.PrivateKey as RSACryptoServiceProvider;
            //privateKey.en
            //_ws.Options.ClientCertificates.Add(cert);
            _connectionToken = new CancellationTokenSource();
            await _ws.ConnectAsync(uri, _connectionToken.Token);

            await Task.Factory.StartNew(ListenAsync, _connectionToken.Token);

            await Task.Factory.StartNew(ListenStateAsync, _connectionToken.Token);
        }
        public void ReadWriteTest()
        {
            var websocket = new ClientWebSocket();
            // Set SubProtocol to AMQPWSB10
            websocket.Options.AddSubProtocol(WebSocketConstants.SubProtocols.Amqpwsb10);
            Uri uri = new Uri("ws://" + IotHubName + ":" + Port + WebSocketConstants.UriSuffix);
            websocket.ConnectAsync(uri, CancellationToken.None).Wait(CancellationToken.None);
            clientWebSocketTransport = new ClientWebSocketTransport(websocket, IotHubName, null, null);

            // Test Write API
            TransportAsyncCallbackArgs args = new TransportAsyncCallbackArgs();
            args.CompletedCallback = onWriteOperationComplete;
            args.SetBuffer(byteArray, 0, byteArray.Length);
            clientWebSocketTransport.WriteAsync(args);

            // Test Read API
            args.CompletedCallback = onReadOperationComplete;
            clientWebSocketTransport.ReadAsync(args);
        }
Exemplo n.º 35
0
        public async Task EndToEnd_ConnectAndClose_Success()
        {
            OwinHttpListener listener = CreateServer(env =>
            {
                var accept = (WebSocketAccept)env["websocket.Accept"];
                Assert.NotNull(accept);

                accept(
                    null,
                    async wsEnv =>
                    {
                        var sendAsync1 = wsEnv.Get<WebSocketSendAsync>("websocket.SendAsync");
                        var receiveAsync1 = wsEnv.Get<WebSocketReceiveAsync>("websocket.ReceiveAsync");
                        var closeAsync1 = wsEnv.Get<WebSocketCloseAsync>("websocket.CloseAsync");

                        var buffer1 = new ArraySegment<byte>(new byte[10]);
                        await receiveAsync1(buffer1, CancellationToken.None);
                        await closeAsync1((int)WebSocketCloseStatus.NormalClosure, "Closing", CancellationToken.None);
                    });

                return TaskHelpers.Completed();
            },
                HttpServerAddress);

            using (listener)
            {
                using (var client = new ClientWebSocket())
                {
                    await client.ConnectAsync(new Uri(WsClientAddress), CancellationToken.None);

                    await client.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
                    WebSocketReceiveResult readResult = await client.ReceiveAsync(new ArraySegment<byte>(new byte[10]), CancellationToken.None);

                    Assert.Equal(WebSocketCloseStatus.NormalClosure, readResult.CloseStatus);
                    Assert.Equal("Closing", readResult.CloseStatusDescription);
                    Assert.Equal(0, readResult.Count);
                    Assert.True(readResult.EndOfMessage);
                    Assert.Equal(WebSocketMessageType.Close, readResult.MessageType);
                }
            }
        }
Exemplo n.º 36
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="uri"></param>
        /// <param name="options"></param>
        /// <exception cref="TimeoutException"></exception>
        /// <exception cref="WebSocketException"></exception>
        /// <returns></returns>
        public async Task ConnectAsync(Uri uri)
        {
            DisposeWebSocketIfNotNull();
            _ws = new System.Net.WebSockets.ClientWebSocket();

            Config?.Invoke(_ws.Options);
            var wsConnectionTokenSource = new CancellationTokenSource(ConnectionTimeout);

            try
            {
                await _ws.ConnectAsync(uri, wsConnectionTokenSource.Token);

                DisposeListenTokenIfNotNull();
                _listenToken = new CancellationTokenSource();
                _            = ListenAsync(_listenToken.Token);
            }
            catch (TaskCanceledException)
            {
                throw new TimeoutException();
            }
        }
Exemplo n.º 37
0
        internal void Run()
        {
            try
            {
                // set the server verification callback if connecting via wss
                if (String.Compare("wss", uri.Scheme, true) == 0)
                {
                    sp = ServicePointManager.FindServicePoint(this.uri);
                    sp.Expect100Continue = true;
                }

                if (!clientWebSocket.ConnectAsync(this.uri, CancellationToken.None).Wait(this.timeout))
                {
                    throw new Exception("timeout");
                }

                // notify listener
                notifyOpen();

                // dispatch frames
                dispatch();
            }
            catch (Exception e)
            {
                String message = "failed to connect";

                for (Exception inner = e.InnerException; inner != null; inner = inner.InnerException)
                {
                    message += (" : " + inner.Message);
                }

                Exception exp = new Exception(message);

                notifyError(exp);
            }
            finally
            {
                // ignore
            }
        }
Exemplo n.º 38
0
    /// <summary>
    /// Connect to the specified host, handshake and prepare the listening task.
    /// </summary>
    /// <param name="host">The URI of the host, usually something like ws://host:port</param>
    /// <param name="timeout">The maximum timeout in milliseconds for the function to execute. Will raise exception when timeout is reached.</param>
    /// <returns></returns>
    internal async System.Threading.Tasks.Task Connect(string host, int timeout)
    {
        try
        {
            System.Uri uri = new System.Uri(host);
            using (var cts = new System.Threading.CancellationTokenSource())
            {
                // Connect
                if (ws == null)
                {
                    ws = new System.Net.WebSockets.ClientWebSocket();
                }
                await ws.ConnectAsync(uri, cts.Token);
            }
            {
                // [HELLO, Realm|uri, Details|dict]
                await Send($"[{(int)Messages.HELLO},\"realm1\"]", timeout);
            }

            StartListen();

            {
                // Should receive the WELCOME
                Response response = await ReceiveExpect(Messages.WELCOME, 0, timeout);

                sessionId = response.ContextSpecificResultId;
            }
        }
        catch (System.Net.WebSockets.WebSocketException e)
        {
            ws.Dispose();
            ws = new System.Net.WebSockets.ClientWebSocket();
            throw new ErrorException(e.ToString());
        }
        catch (System.Exception e)
        {
            throw new ErrorException(e.ToString());
        }
    }
Exemplo n.º 39
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="uri"></param>
        /// <param name="options"></param>
        /// <exception cref="TimeoutException"></exception>
        /// <exception cref="WebSocketException"></exception>
        /// <returns></returns>
        public async Task ConnectAsync(Uri uri)
        {
            if (_ws != null)
            {
                _ws.Dispose();
            }
            _ws = new System.Net.WebSockets.ClientWebSocket();
            Config?.Invoke(_ws.Options);

            _wsWorkTokenSource = new CancellationTokenSource();
            var wsConnectionTokenSource = new CancellationTokenSource(_io.Options.ConnectionTimeout);

            try
            {
                await _ws.ConnectAsync(uri, wsConnectionTokenSource.Token);

                _ = Task.Run(ListenAsync);
            }
            catch (TaskCanceledException)
            {
                throw new TimeoutException();
            }
        }
Exemplo n.º 40
0
 public static async Task ConnectAsync(this ClientWebSocket client, string uri)
 {
     await client.ConnectAsync(new Uri(uri), CancellationToken.None);
 }
Exemplo n.º 41
0
 public Task ConnectAsync(Uri uri, CancellationToken cancellationToken)
 {
     return(webSocket.ConnectAsync(uri, cancellationToken));
 }
Exemplo n.º 42
-1
        public async Task TestConnectWebSocket()
        {
            var wsUrl = Resources.WsServerAddress + "test";
            Assert.IsNotNull(WebServer.Module<WebSocketsModule>(), "WebServer has WebSocketsModule");

            Assert.AreEqual(WebServer.Module<WebSocketsModule>().Handlers.Count, 1, "WebSocketModule has one handler");

#if NET46
            var clientSocket = new ClientWebSocket();
            var ct = new CancellationTokenSource();
            await clientSocket.ConnectAsync(new Uri(wsUrl), ct.Token);

            Assert.AreEqual(WebSocketState.Open, clientSocket.State, "Connection is open");

            var message = new ArraySegment<byte>(System.Text.Encoding.Default.GetBytes("HOLA"));
            var buffer = new ArraySegment<byte>(new byte[1024]);

            await clientSocket.SendAsync(message, WebSocketMessageType.Text, true, ct.Token);
            var result = await clientSocket.ReceiveAsync(buffer, ct.Token);

            Assert.IsTrue(result.EndOfMessage, "End of message is true");
            Assert.IsTrue(System.Text.Encoding.UTF8.GetString(buffer.Array).TrimEnd((char) 0) == "WELCOME", "Final message is WELCOME");
#else
            var clientSocket = new WebSocket(wsUrl);
            clientSocket.Connect();            

            Assert.AreEqual(WebSocketState.Open, clientSocket.State, "Connection is open");

            clientSocket.Send("HOLA");
            await Task.Delay(100);
#endif
        }