找回密码
 会员注册
查看: 107|回复: 0

asp.net WEBSocket简单例子 推送数据

[复制链接]

250

主题

1

回帖

819

积分

管理员

积分
819
发表于 2024-2-29 08:28:30 | 显示全部楼层 |阅读模式

  1. public class SocketHandler
  2. {
  3. public const int BufferSize = 4096; //缓冲区
  4. /// <summary>
  5. /// webSocket 承载
  6. /// </summary>
  7. public WebSocket socket;
  8. /// <summary>
  9. /// webSocket 转换静态
  10. /// </summary>
  11. private static WebSocket webSocket;
  12. private static HttpContext context;
  13. private static byte[] faceJson; //
  14. SocketHandler(WebSocket socket)
  15. {
  16. this.socket = socket;
  17. }
  18. /// <summary>
  19. /// 使用websocket发送json
  20. /// </summary>
  21. /// <param name="body">json实体</param>
  22. /// <returns></returns>
  23. public static async Task Send(FaceCheckinEventArgs body)
  24. {
  25. MsgTemplate msgTemplate = new MsgTemplate();
  26. msgTemplate.Name = body.DeviceName;
  27. msgTemplate.PicUrl = body.PicUrl;
  28. msgTemplate.UpTime = body.RecordTime.ToLocalTime().ToString();
  29. msgTemplate.CarNo = body.CardID;
  30. //序列化
  31. var json = JsonConvert.SerializeObject(msgTemplate);
  32. faceJson = Encoding.UTF8.GetBytes(json);
  33. if (webSocket == null)
  34. return;
  35. //放入数组段
  36. var outgoing = new ArraySegment<byte>(faceJson, 0, faceJson.Length);
  37. //发送json
  38. await webSocket.SendAsync(outgoing, WebSocketMessageType.Text, true, CancellationToken.None);
  39. }
  40. /// <summary>
  41. /// 开启socket
  42. /// </summary>
  43. /// <param name="hc"></param>
  44. /// <param name="n"></param>
  45. /// <returns></returns>
  46. static async Task Acceptor(HttpContext hc, Func<Task> n)
  47. {
  48. if (!hc.WebSockets.IsWebSocketRequest)
  49. return;
  50. var socket = await hc.WebSockets.AcceptWebSocketAsync();
  51. webSocket = socket;
  52. var h = new SocketHandler(socket);
  53. context = hc;
  54. var buffer = new byte[BufferSize];
  55. var seg = new ArraySegment<byte>(buffer);
  56. while(webSocket.State== WebSocketState.Open) //保持开启状态
  57. {
  58. Thread.Sleep(1000);
  59. }
  60. }
  61. /// <summary>
  62. /// 为这个SokKethHANDER使用分支请求管道
  63. /// </summary>
  64. /// <param name="app"></param>
  65. public static void Map(IApplicationBuilder app)
  66. {
  67. app.UseWebSockets();
  68. app.Use(SocketHandler.Acceptor);
  69. }
  70. }
复制代码

来源:https://blog.csdn.net/qq_25702579/article/details/84822704
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 会员注册

本版积分规则

QQ|手机版|心飞设计-版权所有:微度网络信息技术服务中心 ( 鲁ICP备17032091号-12 )|网站地图

GMT+8, 2024-12-26 12:05 , Processed in 0.598749 second(s), 26 queries .

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表