EchoHandler.cs 1009 B

123456789101112131415161718192021222324252627282930313233
  1. using System;
  2. using System.Net.WebSockets;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. using Microsoft.AspNetCore.Http;
  6. namespace BubbleSocketCore.Handlers
  7. {
  8. class EchoHandler : IHandler
  9. {
  10. public void AddSocket(WebSocket webSocket)
  11. {
  12. }
  13. public bool IsListening(HttpRequest request)
  14. {
  15. return request.Path == "/echo";
  16. }
  17. public async Task Listen(HttpContext context, WebSocket webSocket, CancellationToken cancellationToken)
  18. {
  19. var buffer = new byte[1024 * 4];
  20. WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), cancellationToken);
  21. while (!result.CloseStatus.HasValue)
  22. {
  23. await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, cancellationToken);
  24. result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), cancellationToken);
  25. }
  26. await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, cancellationToken);
  27. }
  28. }
  29. }