|
- public class SocketHandler
- {
- public const int BufferSize = 4096; //缓冲区
- /// <summary>
- /// webSocket 承载
- /// </summary>
- public WebSocket socket;
- /// <summary>
- /// webSocket 转换静态
- /// </summary>
- private static WebSocket webSocket;
- private static HttpContext context;
- private static byte[] faceJson; //
- SocketHandler(WebSocket socket)
- {
- this.socket = socket;
- }
- /// <summary>
- /// 使用websocket发送json
- /// </summary>
- /// <param name="body">json实体</param>
- /// <returns></returns>
- public static async Task Send(FaceCheckinEventArgs body)
- {
- MsgTemplate msgTemplate = new MsgTemplate();
- msgTemplate.Name = body.DeviceName;
- msgTemplate.PicUrl = body.PicUrl;
- msgTemplate.UpTime = body.RecordTime.ToLocalTime().ToString();
- msgTemplate.CarNo = body.CardID;
-
- //序列化
- var json = JsonConvert.SerializeObject(msgTemplate);
- faceJson = Encoding.UTF8.GetBytes(json);
- if (webSocket == null)
- return;
- //放入数组段
- var outgoing = new ArraySegment<byte>(faceJson, 0, faceJson.Length);
- //发送json
- await webSocket.SendAsync(outgoing, WebSocketMessageType.Text, true, CancellationToken.None);
- }
- /// <summary>
- /// 开启socket
- /// </summary>
- /// <param name="hc"></param>
- /// <param name="n"></param>
- /// <returns></returns>
- static async Task Acceptor(HttpContext hc, Func<Task> n)
- {
- if (!hc.WebSockets.IsWebSocketRequest)
- return;
- var socket = await hc.WebSockets.AcceptWebSocketAsync();
- webSocket = socket;
- var h = new SocketHandler(socket);
- context = hc;
- var buffer = new byte[BufferSize];
- var seg = new ArraySegment<byte>(buffer);
-
- while(webSocket.State== WebSocketState.Open) //保持开启状态
- {
- Thread.Sleep(1000);
- }
- }
- /// <summary>
- /// 为这个SokKethHANDER使用分支请求管道
- /// </summary>
- /// <param name="app"></param>
- public static void Map(IApplicationBuilder app)
- {
- app.UseWebSockets();
- app.Use(SocketHandler.Acceptor);
- }
- }
复制代码 来源:https://blog.csdn.net/qq_25702579/article/details/84822704 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |
|