如何触发ClientWebSocket关闭

时间:2017-04-21 12:03:57

标签: c# websocket clientwebsocket

基本上我想在执行此代码时关闭此ClientWebSocket时触发

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

是否有任何最佳实践或可能是另一种方法,可以在websocket中关闭当前打开连接

0 个答案:

没有答案