CloseAsync() public method

public CloseAsync ( System closeStatus, string statusDescription, System cancellationToken ) : System.Threading.Tasks.Task
closeStatus System
statusDescription string
cancellationToken System
return System.Threading.Tasks.Task
Example #1
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();
      }
    }
Example #2
0
 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);
         }
     }
 }
        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);
        }
        // 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;
            }
        }
Example #5
0
        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);
                }
            }
        }
 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) { }
 }
        public async Task DisconnectAsync()
        {
            await _ws.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);

            Close(null);
        }
Example #8
0
 public Task CloseAsync(WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken)
 {
     return(webSocket.CloseAsync(closeStatus, statusDescription, cancellationToken));
 }
        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);
        }
Example #10
0
        private void dispatch()
        {
            const Int32 bufferSize = 128 * 1024;

            byte[] buffer   = new byte[bufferSize];
            bool   breakOut = false;

            try
            {
                while (Interlocked.Read(ref state) != CLOSED)
                {
                    ArraySegment <byte> segment = new ArraySegment <byte>(buffer);

                    System.Net.WebSockets.WebSocketReceiveResult result;
                    System.Threading.Tasks.Task <System.Net.WebSockets.WebSocketReceiveResult> r;

                    try
                    {
                        r = clientWebSocket.ReceiveAsync(segment, System.Threading.CancellationToken.None);
                        r.Wait(CancellationToken.None);
                        result = r.Result;

                        if (result.MessageType == WebSocketMessageType.Close)
                        {
                            Task t1 = clientWebSocket.CloseAsync((System.Net.WebSockets.WebSocketCloseStatus)result.CloseStatus, result.CloseStatusDescription, CancellationToken.None);
                            t1.Wait(CancellationToken.None);

                            notifyClose((int)result.CloseStatus, result.CloseStatusDescription);
                            breakOut = true;
                            break;
                        }
                    }
                    catch (Exception e)
                    {
                        notifyError(e);
                        break;
                    }

                    int count = result.Count;
                    while (!result.EndOfMessage)
                    {
                        if (count > buffer.Length)
                        {
                            Task t1 = clientWebSocket.CloseAsync(WebSocketCloseStatus.InvalidPayloadData, "payload too long", CancellationToken.None);
                            t1.Wait(CancellationToken.None);
                            notifyClose((int)WebSocketCloseStatus.InvalidPayloadData, "payload too long");
                            return;
                        }

                        segment = new ArraySegment <byte>(buffer, count, buffer.Length - count);

                        r = clientWebSocket.ReceiveAsync(segment, CancellationToken.None);
                        r.Wait(CancellationToken.None);
                        result = r.Result;

                        if (result.MessageType == WebSocketMessageType.Close)
                        {
                            Task t1 = clientWebSocket.CloseAsync((System.Net.WebSockets.WebSocketCloseStatus)result.CloseStatus, result.CloseStatusDescription, CancellationToken.None);
                            t1.Wait(CancellationToken.None);

                            notifyClose((int)result.CloseStatus, result.CloseStatusDescription);
                            breakOut = true;
                            break;
                        }
                        else if (result.Count == 0)
                        {
                            // filled the buffer, resize it
                            var newBuffer = new byte[buffer.Length + bufferSize];
                            Array.Copy(buffer, newBuffer, buffer.Length);
                            buffer = newBuffer;
                        }
                        if (breakOut)
                        {
                            break;
                        }

                        count += result.Count;
                    }

                    // now invoke the callback.
                    if (count > 0)
                    {
                        notifyMessage(buffer, count);
                    }
                }
            }
            catch (Exception) { return; }

            return;
        }
Example #11
0
        public async Task DisconnectAsync()
        {
            await _ws.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);

            OnClosed("io client disconnect");
        }
        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)
                    {
                    }
                }
            }
        }
Example #13
0
        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 = "";
                    }
 
                }
                
                
            }
        }
Example #14
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();
                }


            }

        }