index.ashx 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <%@ WebHandler Language="C#" Class="index" %>
  2. using System;
  3. using System.Web;
  4. using System.Collections.Generic;
  5. using Fleck;
  6. using System.Linq;
  7. /// <summary>
  8. /// 测试WebSocket服务
  9. /// xuwei add 2024-03-26
  10. /// </summary>
  11. public class index : IHttpHandler
  12. {
  13. public static List<IWebSocketConnection> allScokets;
  14. public static WebSocketServer server;
  15. public void ProcessRequest(HttpContext context)
  16. {
  17. //启动服务
  18. if (context.Request["start"] is object)
  19. {
  20. start();
  21. context.Response.Write("服务启动成功!");
  22. }
  23. //发送数据
  24. if (context.Request["barcode"] is object)
  25. {
  26. foreach (var socket in allScokets.ToList())
  27. {
  28. socket.Send("条码:" + context.Request["barcode"].ToString());
  29. }
  30. }
  31. }
  32. //启动服务
  33. public static void start()
  34. {
  35. allScokets = new List<IWebSocketConnection>();
  36. server = new WebSocketServer("ws://127.0.0.1:9200");
  37. server.Start(scoket =>
  38. {
  39. scoket.OnOpen = () => { allScokets.Add(scoket); };
  40. scoket.OnClose = () => { allScokets.Remove(scoket); };
  41. scoket.OnMessage = message => { allScokets.ToList().ForEach(s => s.Send(message)); };
  42. });
  43. }
  44. public bool IsReusable
  45. {
  46. get
  47. {
  48. return false;
  49. }
  50. }
  51. }