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


C# ClientWebSocket.CloseAsync方法代码示例

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


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

示例1: Main

    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();
      }
    }
开发者ID:ibebbs,项目名称:Rxx,代码行数:57,代码来源:WebSocketLab.cs

示例2: Receive

 private static async Task Receive(ClientWebSocket webSocket)
 {
     byte[] buffer = new byte[receiveChunkSize];
     while (webSocket.State == WebSocketState.Open)
     {                
         var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
         if (result.MessageType == WebSocketMessageType.Close)
         {
             await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
         }
         else
         {
             LogStatus(true, buffer, result.Count);
         }
     }
 }
开发者ID:paulbatum,项目名称:WebSocket-Samples,代码行数:16,代码来源:Client.cs

示例3: ClientWebSocketTransportReadWithoutConnectTest

        public async Task ClientWebSocketTransportReadWithoutConnectTest()
        {
            var websocket = new ClientWebSocket();
            var clientWebSocketTransport = new ClientWebSocketTransport(websocket, null, null);
            var args = new TransportAsyncCallbackArgs();
            var byteArray = new byte[10];
            args.SetBuffer(byteArray, 0, 10);
            if (clientWebSocketTransport.ReadAsync(args))
            {
                while (!readComplete)
                {
                    Thread.Sleep(TimeSpan.FromSeconds(1));
                }
            }

            await websocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
        }
开发者ID:pierreca,项目名称:azure-iot-sdks,代码行数:17,代码来源:ClientWebSocketTransportTests.cs

示例4: Receive

        // Define other methods and classes here
        private async Task Receive(ClientWebSocket webSocket)
        {
            var buffer = new byte[64];
            while (webSocket.State == WebSocketState.Open)
            {
                var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
                if (result.MessageType == WebSocketMessageType.Close)
                {
                    await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
                }
                else
                {
                    DeserializeAndEnqueue(buffer, result.Count);
                }

                //if(Console.KeyAvailable)
                //    break;
            }
        }
开发者ID:kjellski,项目名称:RxUncontexted,代码行数:20,代码来源:UncontextedWebsocketSubscriber.cs

示例5: Receive

        private async Task Receive(ClientWebSocket socket)
        {
            var buffer = new byte[2048];
            while (socket.State == WebSocketState.Open)
            {
                var result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
                if (result.MessageType == WebSocketMessageType.Close)
                {
                    await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
                }
                else
                {
                    var json = Encoding.ASCII.GetString(buffer).TrimEnd('\0');
                    var notification = JsonConvert.DeserializeObject<WebSocketClientNotification>(json);

                    NotificationReceived?.Invoke(this, new WebSocketClientNotificationEventArgs(notification));

                    Array.Clear(buffer,0,buffer.Length);
                }
            }
        }
开发者ID:Zmote,项目名称:WPF-Miniprojekt,代码行数:21,代码来源:WebSocketClient.cs

示例6: ReceiveWebsocketMessageAndAppend

 private static void ReceiveWebsocketMessageAndAppend(ClientWebSocket client, List<String> messages)
 {
     var receiveBuffer = new byte[1024];
     var receiveBufferSegment = new ArraySegment<byte>(receiveBuffer);
     try
     {
         var result = client.ReceiveAsync(receiveBufferSegment, CancellationToken.None).Result;
         if (result.Count > 0)
         {
             var message = Encoding.Default.GetString(receiveBuffer.Take(result.Count).ToArray());
             if (message.Contains("error"))
             {
                 throw new Exception("websocket returned an error message");
             }
             else if (message.Contains("close"))
             {
                 client.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
             }
             messages.Add(message);
         }
     }
     catch (Exception) { }
 }
开发者ID:stefanschneider,项目名称:garden-windows,代码行数:23,代码来源:ConsumerCanRunAProcessSpec.cs

示例7: Echo

        public async Task Echo()
        {
            var snd = "Hello, World!";
            var rcv = string.Empty;

            _echoFactory.OnReceiveAsyncCallBack = (session, buffer, tuple) =>
            {
                var messageLength = tuple.Item3;
                var actual = buffer.Actualize(messageLength);
                

                rcv = Encoding.UTF8.GetString(actual);
                Assert.AreEqual(snd, rcv);

                // send it back
                session.Send(rcv);
                return Task.FromResult(0);
            };


            ClientWebSocket clientWSocket = new ClientWebSocket();
            await clientWSocket.ConnectAsync(new Uri(_serverAddressPublish), CancellationToken.None);

            // send 
            await clientWSocket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes(snd)),
                                          WebSocketMessageType.Text,
                                          true,
                                          CancellationToken.None);



            await Task.Delay(100);
            var socketRecieved = await ReceiveFromSocket(clientWSocket);

            Assert.AreEqual(snd, socketRecieved);
            await clientWSocket.CloseAsync(WebSocketCloseStatus.NormalClosure,  "close",CancellationToken.None);
        }
开发者ID:khenidak,项目名称:WebSocketsServer,代码行数:37,代码来源:SocketServer.Tests.cs

示例8: ErrorInWebSocket_Disconnected

        public async Task ErrorInWebSocket_Disconnected()
        {
            ManualResetEvent sync = new ManualResetEvent(false);
            OwinHttpListener listener = CreateServer(env =>
                {
                    var accept = (WebSocketAccept)env["websocket.Accept"];
                    Assert.NotNull(accept);

                    accept(
                        null,
                        async wsEnv =>
                        {
                            sync.Set();
                            throw new Exception("Application WebSocket error.");
                        });

                    return Task.FromResult(0);
                },
                HttpServerAddress);

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

                    try
                    {
                        Assert.True(sync.WaitOne(500));
                        await client.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
                        Assert.Equal(string.Empty, "A WebSocketException was expected.");
                    }
                    catch (WebSocketException)
                    {
                    }
                }
            }
        }
开发者ID:Kstal,项目名称:Microsoft.Owin,代码行数:38,代码来源:OwinWebSocketTests.cs

示例9: Receive

        public async Task Receive(ClientWebSocket webSocket)
        {
            byte[] buffer = new byte[1024];
            string TempString = "";
            while (webSocket.State == WebSocketState.Open)
            {
                
                var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
                if (result.MessageType == WebSocketMessageType.Close)
                {
                    await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);

                }
                else
                {
                    TempString = Encoding.UTF8.GetString(buffer);
                    TempString = TempString.Remove(result.Count);
                    if (TempString.Substring(TempString.Length - 1, 1) == "}" || TempString == "hello")
                    {
                        DecodeServerPacket(TempString);
                        TempString = "";
                    }
 
                }
                
                
            }
        }
开发者ID:chaoscode,项目名称:CSharp-RustIO-Client,代码行数:28,代码来源:Form1.cs

示例10: startRunner

        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();
                }


            }

        }
开发者ID:Shuffle-Game,项目名称:AnyCardGame,代码行数:54,代码来源:Program.cs


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