public static WebSocketMessage ReadFrom(bool fromServer, byte[] payload)
 {
     using (MemoryStream memoryStream = new MemoryStream(payload))
         return(WebSocketMessage.ReadFrom(fromServer, (Stream)memoryStream));
 }
        private async Task Receive(ClientWebSocket webSocket)
        {
            ClientWebSocketHandler webSocketHandler = this;
            ArraySegment <byte>    inputSegment     = new ArraySegment <byte>(new byte[65536]);

            using (MemoryStream ms = new MemoryStream())
            {
                while (webSocket.State == WebSocketState.Open)
                {
                    try
                    {
                        WebSocketReceiveResult async = await webSocket.ReceiveAsync(inputSegment, CancellationToken.None);

                        if (async.MessageType == WebSocketMessageType.Close)
                        {
                            try
                            {
                                if (webSocketHandler.Disconnected != null)
                                {
                                    await webSocketHandler.Disconnected(webSocketHandler, true);
                                }
                                await webSocket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "Endpoint demanded closure", CancellationToken.None);

                                Console.WriteLine("Endpoint demanded closure");
                                break;
                            }
                            catch
                            {
                                break;
                            }
                        }
                        else
                        {
                            ms.Write(inputSegment.Array, inputSegment.Offset, async.Count);
                            if (async.EndOfMessage)
                            {
                                ms.GetBuffer();
                                ms.Seek(0L, SeekOrigin.Begin);
                                WebSocketMessage message = WebSocketMessage.ReadFrom(true, (Stream)ms);
                                Console.WriteLine("Message:" + (object)ms.Length + " " + (object)message);
                                if (webSocketHandler.MessageReceived != null)
                                {
                                    webSocketHandler.MessageReceived(message, webSocketHandler);
                                }
                                ms.Seek(0L, SeekOrigin.Begin);
                            }
                        }
                    }
                    catch (WebSocketException ex)
                    {
                        if (webSocketHandler.Disconnected == null)
                        {
                            break;
                        }
                        await webSocketHandler.Disconnected(webSocketHandler, false);

                        break;
                    }
                }
            }
        }