0

基本上我想在执行此代码时关闭此 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 中的当前打开连接

4

0 回答 0