如何查看websocket是否关闭?

时间:2018-08-03 18:16:17

标签: c# websocket asp-net-core-spa-services

.NET Core Websocket服务器,我试图了解为什么我从来没有得到WebSocketMessageType.Close

我与客户端连接到服务器,我发送了一些东西,接收了一些东西,然后客户端关闭。为什么服务器仍将结果显示为WebSocketReceiveResult.Text

客户

static async Task Main(string[] args)
        {
            using (ClientWebSocket socket = new ClientWebSocket())
            {
                await socket.ConnectAsync(Constants.uri, CancellationToken.None);
                int id;
                if (!Int32.TryParse(Console.ReadLine(), out id))
                {
                    id = 5;
                }
                MyRandomClass player = new MyRandomClass();
                ReadOnlyMemory<byte> bytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(player));
                await socket.SendAsync(bytes, WebSocketMessageType.Text, true, CancellationToken.None);
                var byteStore = ArrayPool<byte>.Shared.Rent(1024);
                var result = await socket.ReceiveAsync(byteStore, CancellationToken.None);
                Console.WriteLine("Hello World!");
                await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "normal", CancellationToken.None);
            }
        }

服务器

public async Task AddClientAsync(WebSocketManager manager)
        {
            Memory<byte> rawReceived = new byte[1024];

            WebSocket clientSocket = await manager.AcceptWebSocketAsync();

            while (true)
            {

                ValueWebSocketReceiveResult socketResult = await clientSocket.ReceiveAsync(rawReceived, CancellationToken.None);

                string dataString = Encoding.UTF8.GetString(rawReceived.Slice(0, socketResult.Count).ToArray());


                MyRandomClass request= JsonConvert.DeserializeObject<MyRandomClass>(dataString);

                    if (socketResult.MessageType == WebSocketMessageType.Close )
                    {
                       //at second iteration still not entering here !!!
                        break;
                    }
                }
                ReadOnlyMemory<byte> payload = Encoding.UTF8.GetBytes("sent");
                await clientSocket.SendAsync(payload, WebSocketMessageType.Text, true, CancellationToken.None);
            }

PS :我在第一次迭代(在服务器上)调试服务器时,会发送和接收消息。但是,我不明白为什么在第二次迭代中WebSocketMessageType仍然存在Text而非Close

P.S2 当使用google websocket浏览器扩展程序时,我确实得到了WebSocketMessageType.Close
https://chrome.google.com/webstore/detail/simple-websocket-client/pfdhoblngboilpfeibdedpjgfnlcodoo
因此,我想我必须在客户端上添加一些东西才能发送,以便能够在服务器上获取Close消息。

什么是找出WebSocket何时断开连接并挂接到该时刻的可靠方法?

0 个答案:

没有答案