当前位置: 首页>>代码示例>>C#>>正文


C# WebSockets.ClientWebSocket类代码示例

本文整理汇总了C#中System.Net.WebSockets.ClientWebSocket的典型用法代码示例。如果您正苦于以下问题:C# ClientWebSocket类的具体用法?C# ClientWebSocket怎么用?C# ClientWebSocket使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


ClientWebSocket类属于System.Net.WebSockets命名空间,在下文中一共展示了ClientWebSocket类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: BasicRoundTrip

		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();
		}
开发者ID:BrannonKing,项目名称:Kts.Remoting,代码行数:34,代码来源:SystemWebSocketsToVtortolaCircle.cs

示例2: Connect

        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();
                }
            }
        }
开发者ID:RussBaz,项目名称:PTVS,代码行数:31,代码来源:WebSocketTransport.cs

示例3: TestConnectWebSocket

        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");
        }
开发者ID:ngdadu,项目名称:embedio,代码行数:26,代码来源:WebSocketsModuleTest.cs

示例4: WebsocketBasic

        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));
                    }
                }
            }
        }
开发者ID:Xamarui,项目名称:Katana,代码行数:27,代码来源:WebSocketTest.cs

示例5: WebSocketWrapper

 public WebSocketWrapper(string uri)
 {
     _ws = new ClientWebSocket();
     _ws.Options.KeepAliveInterval = TimeSpan.FromSeconds(20);
     _uri = new Uri(uri);
     _cancellationToken = _cancellationTokenSource.Token;
 }
开发者ID:IGarcia1121,项目名称:AgarIO-Bot,代码行数:7,代码来源:WebSocketWrapper.cs

示例6: Initialize

        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);
        }
开发者ID:modulexcite,项目名称:PowerShellEditorServices,代码行数:34,代码来源:WebsocketClientChannel.cs

示例7: RunSample

        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));
            }
        }
开发者ID:andreychizhov,项目名称:microsoft-aspnet-samples,代码行数:25,代码来源:Program.cs

示例8: ConnectAndStartReceivingToWebSocket

        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.");
            }
        }
开发者ID:kjellski,项目名称:RxUncontexted,代码行数:25,代码来源:UncontextedWebsocketSubscriber.cs

示例9: Setup

		public void Setup ()
		{
			listener = new HttpListener ();
			listener.Prefixes.Add ("http://localhost:" + Port + "/");
			listener.Start ();
			socket = new ClientWebSocket ();
		}
开发者ID:nslAnil,项目名称:mono,代码行数:7,代码来源:ClientWebSocketTest.cs

示例10: RefreshInternal

        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();
        }
开发者ID:modulexcite,项目名称:WebSync,代码行数:28,代码来源:BrowserController.cs

示例11: RunSample

        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));
            //}
        }
开发者ID:Indifer,项目名称:Test,代码行数:32,代码来源:Program.cs

示例12: ReadWriteTest

        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));
        }
开发者ID:Fricsay,项目名称:azure-iot-sdks,代码行数:29,代码来源:ClientWebSocketTransportTests.cs

示例13: Connect

        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();
                }
            }
        }
开发者ID:paulbatum,项目名称:WebSocket-Samples,代码行数:28,代码来源:Client.cs

示例14: WebSocketTransport

 public WebSocketTransport()
 {
     this._socket = new ClientWebSocket();
     this._socket.Options.AddSubProtocol("wamp");
     this._cts = new CancellationTokenSource();
     this._serializer = new DapperWare.Serialization.JsonSerializer();
 }
开发者ID:azchohfi,项目名称:MiniWamp,代码行数:7,代码来源:WebSocketTransport.cs

示例15: BasicRoundTrip

		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();
		}
开发者ID:BrannonKing,项目名称:Kts.Remoting,代码行数:31,代码来源:SystemWebSocketsFullCircle.cs


注:本文中的System.Net.WebSockets.ClientWebSocket类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。