public void ProcessRequest(HttpContext context)
 {
     if (context.IsWebSocketRequest)
     {
         var chatUser = new ChatUser
         {
             UserName = context.Request.QueryString["name"]
         };
         ChatApp.AddUser(chatUser);
         context.AcceptWebSocketRequest(chatUser.HandleWebSocketAsync);
     }
 }
        public async Task HandleWebSocketAsync(WebSocketContext webSocketContext)
        {
            _context = webSocketContext;
            var receiveBuffer = new byte[MaxMessageSize];
            var socket        = _context.WebSocket;

            while (socket.State == WebSocketState.Open)
            {
                var receiveResult =
                    await socket.ReceiveAsync(new ArraySegment <byte>(receiveBuffer), CancellationToken.None);

                switch (receiveResult.MessageType)
                {
                case WebSocketMessageType.Close:
                    await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);

                    break;

                case WebSocketMessageType.Binary:
                    await
                    socket.CloseAsync(WebSocketCloseStatus.InvalidMessageType, "Cannot accept binary frame",
                                      CancellationToken.None);

                    break;

                case WebSocketMessageType.Text:
                    var receivedString = _defaultEncoding.GetString(receiveBuffer, 0, receiveResult.Count);
                    var echoString     = string.Concat(UserName, " said: ", receivedString);
                    // var outputBuffer = new ArraySegment<byte>(_defaultEncoding.GetBytes(echoString));
                    ChatApp.BroadcastMessage(echoString);
                    break;

                default:
                    goto case WebSocketMessageType.Close;
                }
            }
        }