예제 #1
0
        public async Task HandleWebSocket(WebSocketContext wsContext)
        {
            _context = wsContext;
            const int maxMessageSize = 1024;

            byte[]    receiveBuffer = new byte[maxMessageSize];
            WebSocket socket        = _context.WebSocket;

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

                if (receiveResult.MessageType == WebSocketMessageType.Close)
                {
                    await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
                }
                else if (receiveResult.MessageType == WebSocketMessageType.Binary)
                {
                    await socket.CloseAsync(WebSocketCloseStatus.InvalidMessageType, "Cannot accept binary frame", CancellationToken.None);
                }
                else
                {
                    var receivedString = Encoding.UTF8.GetString(receiveBuffer, 0, receiveResult.Count);
                    var echoString     = string.Concat(UserName, " said: ", receivedString);
                    ArraySegment <byte> outputBuffer = new ArraySegment <byte>(Encoding.UTF8.GetBytes(echoString));

                    ChatApp.BroadcastMessage(echoString);
                }
            }
        }
예제 #2
0
 public void ProcessRequest(HttpContext context)
 {
     if (context.IsWebSocketRequest)
     {
         var chatuser = new ChatUser();
         chatuser.UserName = context.Request.QueryString["name"];
         ChatApp.AddUser(chatuser);
         context.AcceptWebSocketRequest(chatuser.HandleWebSocket);
         //context.AcceptWebSocketRequest(HandleWebSocket);
     }
 }