SanSYS

Untitled

Apr 29th, 2015
16,665
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.04 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Net.WebSockets;
  4. using System.Text;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. using System.Web;
  8. using System.Web.WebSockets;
  9.  
  10. namespace DemoWebSockets
  11. {
  12.     public class CustomWS : IHttpHandler
  13.     {
  14.         static List<WebSocket> clients = new List<WebSocket>();
  15.  
  16.         public void ProcessRequest(HttpContext context)
  17.         {
  18.             if (context.IsWebSocketRequest)
  19.             {
  20.                 context.AcceptWebSocketRequest(ProcessWSChat);
  21.             }
  22.         }
  23.  
  24.         private async Task ProcessWSChat(AspNetWebSocketContext context)
  25.         {
  26.             WebSocket socket = context.WebSocket;
  27.  
  28.             clients.Add(socket);
  29.  
  30.             bool isEnabled = true;
  31.  
  32.             while (isEnabled)
  33.             {
  34.                 ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[1024]);
  35.  
  36.                 WebSocketReceiveResult result = await socket.ReceiveAsync(buffer, CancellationToken.None);
  37.  
  38.                 if (result.MessageType == WebSocketMessageType.Close)
  39.                 {
  40.                     isEnabled = false;
  41.  
  42.                     clients.Remove(socket);
  43.                 }
  44.                 else
  45.                 {
  46.                     string userMessage = string.Format("You sent: {0} at {1:mm:ss.fff}", Encoding.UTF8.GetString(buffer.Array, 0, result.Count), DateTime.Now);
  47.  
  48.                     byte[] messageBytes = Encoding.UTF8.GetBytes(userMessage);
  49.  
  50.                     buffer = new ArraySegment<byte>(messageBytes);
  51.  
  52.                     Parallel.ForEach(clients, p =>
  53.                     {
  54.                         if (p.State == WebSocketState.Open)
  55.                         {
  56.                             p.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);
  57.                         }
  58.                     });
  59.                 }
  60.             }
  61.         }
  62.  
  63.         public bool IsReusable
  64.         {
  65.             get
  66.             {
  67.                 return false;
  68.             }
  69.         }
  70.     }
  71. }
Advertisement
Add Comment
Please, Sign In to add comment