0

Basically I want to trigger when I can close this ClientWebSocket when I execute this code

 static void Main(string[] args)
    {
        Thread.Sleep(1000);
        Connect("ws://endpointfrompublicurl").Wait();
        Console.WriteLine("Press any key to exit...");
        Console.ReadKey();
    }

public static async Task Connect(string uri, ClientWebSocket webSocket)
    {
        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();
            }
        }
    }

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

Is there any best practice or perhaps another approach for possibility close current open connection in websocket

poli
  • 67
  • 1
  • 1
  • 7
  • Perhaps you are looking for 'using' directive which is very good friend of Dispose Pattern https://msdn.microsoft.com/en-us/library/b1yfkh5e(v=vs.110).aspx – Eugene Komisarenko Apr 21 '17 at 12:56
  • thank you for your reply, but with 'using' when this code hit the await Task.WhenAll(Receive(webSocket), Send(webSocket)); it keep running until the task is done, basically what I want try to do is, how can I interupt that proccess? so that I can use some trigger manually to stop the process, thank you – poli Apr 25 '17 at 08:40

0 Answers0