WebSocketForwardModule.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using System;
  2. using System.Net;
  3. using System.Net.Sockets;
  4. using System.Net.WebSockets;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. using System.Web;
  8. namespace AspNetTools
  9. {
  10. public static class WebSocketForwardModule
  11. {
  12. public static void ForwardCurrentContext(string opKey, string opValue, IPEndPoint endPoint, int bufferSize = 1024)
  13. {
  14. var ctx = HttpContext.Current;
  15. var req = HttpContext.Current.Request;
  16. if (req.QueryString[opKey] == opValue)
  17. {
  18. ctx.Handler = null;
  19. var rsp = HttpContext.Current.Response;
  20. //if (ctx.IsDebuggingEnabled == false && req.IsSecureConnection == false)
  21. //{
  22. // rsp.ContentType = "text/html";
  23. // rsp.Write("Prod env is Secure Connection required");
  24. // ctx.ApplicationInstance.CompleteRequest();
  25. // return;
  26. //}
  27. if (ctx.IsWebSocketRequest)
  28. {
  29. ctx.AcceptWebSocketRequest(async (ws) =>
  30. {
  31. var fcl = new TcpClient();
  32. fcl.Connect(endPoint);
  33. var ns = fcl.GetStream();
  34. var tIn = Task.Run(async () =>
  35. {
  36. var buf = new byte[bufferSize];
  37. var arrSeg = new ArraySegment<byte>(buf);
  38. while (ws.WebSocket.CloseStatus.HasValue == false)
  39. {
  40. var x = await ws.WebSocket.ReceiveAsync(arrSeg, CancellationToken.None);
  41. await ns.WriteAsync(buf, 0, x.Count);
  42. }
  43. });
  44. var tOut = Task.Run(async () =>
  45. {
  46. var buf = new byte[bufferSize];
  47. while (ws.WebSocket.CloseStatus.HasValue == false)
  48. {
  49. var count = await ns.ReadAsync(buf, 0, buf.Length);
  50. var arrSeg = new ArraySegment<byte>(buf, 0, count);
  51. await ws.WebSocket.SendAsync(arrSeg, WebSocketMessageType.Binary, true, CancellationToken.None);
  52. }
  53. });
  54. Task.WaitAll(tIn, tOut);
  55. fcl.Close();
  56. });
  57. }
  58. else
  59. {
  60. rsp.ContentType = "text/html";
  61. rsp.Write("Welcome back. Master!");
  62. }
  63. }
  64. }
  65. }
  66. }