Esempio n. 1
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.");
            }
        }
		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();
		}
Esempio n. 4
0
 public WebSocketWrapper(string uri)
 {
     _ws = new ClientWebSocket();
     _ws.Options.KeepAliveInterval = TimeSpan.FromSeconds(20);
     _uri = new Uri(uri);
     _cancellationToken = _cancellationTokenSource.Token;
 }
Esempio n. 5
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));
            //}
        }
		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();
		}
Esempio n. 7
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();
                }
            }
        }
Esempio n. 8
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 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));
            }
        }
        public async Task ReadWriteTest()
        {
            var websocket = new ClientWebSocket();
            // Set SubProtocol to AMQPWSB10
            websocket.Options.AddSubProtocol(WebSocketConstants.SubProtocols.Amqpwsb10);
            Uri uri = new Uri("ws://" + IotHubName + ":" + Port + WebSocketConstants.UriSuffix);
            await websocket.ConnectAsync(uri, CancellationToken.None);
            clientWebSocketTransport = new ClientWebSocketTransport(websocket, null, null);

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

            // Test Read API
            args.CompletedCallback = onReadOperationComplete;
            if (clientWebSocketTransport.ReadAsync(args))
            {
                while (!readComplete)
                {
                    Thread.Sleep(TimeSpan.FromSeconds(1));
                }
            }

            // Once Read operation is complete, close websocket transport
            // Test Close API
            await clientWebSocketTransport.CloseAsync(TimeSpan.FromSeconds(30));
        }
Esempio n. 11
0
		public void Setup ()
		{
			listener = new HttpListener ();
			listener.Prefixes.Add ("http://localhost:" + Port + "/");
			listener.Start ();
			socket = new ClientWebSocket ();
		}
        /// <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();
            }
        }
Esempio n. 13
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;
        }
Esempio n. 14
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");
        }
Esempio n. 15
0
        private void RefreshInternal(string debuggerUrl)
        {
            if (string.IsNullOrEmpty(debuggerUrl))
                return;

            ClientWebSocket connection = new ClientWebSocket();
            connection.ConnectAsync(new Uri(debuggerUrl), _token).Wait();

            PageReloadRequest request = new PageReloadRequest();
            string rawRequest = request.ToJson();

            var data = new ArraySegment<byte>(Encoding.UTF8.GetBytes(rawRequest));
            connection.SendAsync(data, WebSocketMessageType.Text, true, _token).Wait();
            var buffer = new ArraySegment<byte>(new byte[1024]);
            Task<WebSocketReceiveResult> receiveAsync = connection.ReceiveAsync(buffer, _token);
            receiveAsync.Wait();

            string rawResponse = Encoding.UTF8.GetString(buffer.Array, 0, receiveAsync.Result.Count);
            DebugProtocolResponse response = rawResponse.FromJson<DebugProtocolResponse>();

            if (null != response.Error)
            {
                Trace.TraceWarning("Browser returned an error as a response to reload request: {0}",
                                   response.Error.Message);
            }

            connection.Dispose();
        }
Esempio n. 16
0
 public WebSocketTransport()
 {
     this._socket = new ClientWebSocket();
     this._socket.Options.AddSubProtocol("wamp");
     this._cts = new CancellationTokenSource();
     this._serializer = new DapperWare.Serialization.JsonSerializer();
 }
        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);
        }
        protected override void Initialize(IMessageSerializer messageSerializer)
        {
            try
            {
                this.socket = new ClientWebSocket();
                this.socket.ConnectAsync(new Uri(serverUrl), CancellationToken.None).Wait();
            }
            catch (AggregateException ex)
            {
                var wsException= ex.InnerExceptions.FirstOrDefault() as WebSocketException;
                if (wsException != null)
                {
                    Logger.Write(LogLevel.Warning,
                        string.Format("Failed to connect to WebSocket server. Error was '{0}'", wsException.Message));
                   
                }

                throw;
            }
            
            this.inputStream = new ClientWebSocketStream(socket);
            this.outputStream = new ClientWebSocketStream(socket);

            // Set up the message reader and writer
            this.MessageReader =
                new MessageReader(
                    this.inputStream,
                    messageSerializer);

            this.MessageWriter =
                new MessageWriter(
                    this.outputStream,
                    messageSerializer);
        }
Esempio n. 19
0
        /// <summary>
        /// Initializes a new instance of the <see cref="WebSocketConnection"/> class.
        /// </summary>
        /// <param name="serverUri">
        /// The server uri.
        /// </param>
        public WebSocketConnection(Uri serverUri)
        {
            this.serverUri = serverUri;
            this.client = new ClientWebSocket();

            this.sendQueue = new BlockingCollection<string>();
            this.buffer = new ArraySegment<byte>(new byte[1024]);
        }
 public async Task ClientWebSocketChannelReadWithoutConnectTest()
 {
     var websocket = new ClientWebSocket();
     clientWebSocketChannel = new ClientWebSocketChannel(null, websocket);
     var threadLoop = new SingleThreadEventLoop("MQTTExecutionThread", TimeSpan.FromSeconds(1));
     await threadLoop.RegisterAsync(clientWebSocketChannel);
     clientWebSocketChannel.Read();
 }
        public WsCommunicationClient(string baseAddress)
        {
            Logger.Debug("ctor: {0}", baseAddress);

            this.clientWebSocket = new ClientWebSocket();

            this.BaseAddress = baseAddress;
        }
 protected WebSocketWrapper(string uri)
 {
 	System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
     _ws = new ClientWebSocket();
     _ws.Options.KeepAliveInterval = TimeSpan.FromSeconds(20);
     _uri = new Uri(uri);
     _cancellationToken = _cancellationTokenSource.Token;
 }
Esempio n. 23
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);
        }
Esempio n. 24
0
		public Task Disconnect()
		{
			string ignored;
			while (_sendQueue.TryDequeue(out ignored)) { }
			_webSocket.Dispose();
			_webSocket = new ClientWebSocket();
            return TaskHelper.CompletedTask;
		}
 public ClientWebSocketTransport(ClientWebSocket webSocket, EndPoint localEndpoint, EndPoint remoteEndpoint)
     : base("clientwebsocket")
 {
     this.webSocket = webSocket;
     this.localEndPoint = localEndpoint;
     this.remoteEndPoint = remoteEndpoint;
     this.writeCancellationTokenSource = new CancellationTokenSource();
 }
 public void ClientWebSocketTransportWriteWithoutConnectTest()
 {
     var websocket = new ClientWebSocket();
     var clientWebSocketTransport = new ClientWebSocketTransport(websocket, null, null);
     var args = new TransportAsyncCallbackArgs();
     args.SetBuffer(byteArray, 0, byteArray.Length);
     clientWebSocketTransport.WriteAsync(args);
 }
Esempio n. 27
0
        public Task Disconnect()
        {
            string ignored;
            while (_sendQueue.TryDequeue(out ignored)) { }
            
            _webSocket = null;

            return TaskHelper.CompletedTask;
        }
Esempio n. 28
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();
		}
Esempio n. 29
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();
      }
    }
 public void ClientWebSocketTransportReadTest()
 {
     var websocket = new ClientWebSocket();
     var clientWebSocketTransport = new ClientWebSocketTransport(websocket, IotHubName, null, null);
     TransportAsyncCallbackArgs args = new TransportAsyncCallbackArgs();
     byte[] byteArray = new byte[10];
     args.SetBuffer(byteArray, 0, 10);
     clientWebSocketTransport.ReadAsync(args);
 }
Esempio n. 31
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
 }
Esempio n. 32
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);
        }
Esempio n. 33
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
        }
Esempio n. 34
0
        public Task Disconnect()
        {
            string ignored;

            while (_sendQueue.TryDequeue(out ignored))
            {
            }

            _webSocket = null;

            return(TaskHelper.CompletedTask);
        }
Esempio n. 35
0
 static bool CheckManagedWebSocketRequired()
 {
     try
     {
         using (var clientWebSocket = new System.Net.WebSockets.ClientWebSocket())
         {
             return(false);
         }
     }
     catch (PlatformNotSupportedException)
     {
         return(true);
     }
 }
        /// <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);
        }
Esempio n. 37
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);
        }
Esempio n. 38
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();
            }
        }
Esempio n. 39
0
        // internal API /////////////////////////////////////////////////////////////
        internal WebSocket(Uri uri, WebSocketListener listener)
        {
            bool ignoreCase = true;

            this.uri      = uri;
            this.listener = listener;

            this.protocols = new ArrayList();

            if ((String.Compare("ws", uri.Scheme, ignoreCase) != 0) &&
                (String.Compare("wss", uri.Scheme, ignoreCase) != 0))
            {
                throw new Exception("URI scheme must be 'ws' or 'wss'");
            }

            clientWebSocket = new ClientWebSocket();
            options         = clientWebSocket.Options;

            // turn off pongs from client to server.
            options.KeepAliveInterval = new System.TimeSpan(0);
        }
Esempio n. 40
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());
        }
    }
Esempio n. 41
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();
            }
        }
Esempio n. 42
0
 public static async Task ConnectAsync(this ClientWebSocket client, string uri)
 {
     await client.ConnectAsync(new Uri(uri), CancellationToken.None);
 }
Esempio n. 43
0
 public TClientWebSocket CreateClient(ClientWebSocket client)
 {
     client = client ?? throw new ArgumentNullException(nameof(client));
     return((TClientWebSocket)_cache.Activator(_services, new object[] { client }));
 }
Esempio n. 44
0
 public WebSocketClient()
 {
     _clientWebSocket = new System.Net.WebSockets.ClientWebSocket();
     //_clientWebSocket.SubProtocol = "arraybuffer";
 }
 public FrameworkClientWebSocket(System.Net.WebSockets.ClientWebSocket client)
 {
     this.client  = client;
     this.Options = new FrameworkClientWebSocketOptions(this.client.Options);
 }
Esempio n. 46
0
 public ClientWebSocket(System.Net.WebSockets.ClientWebSocket socket)
 {
     mSocket = socket;
 }
Esempio n. 47
-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
        }