asp.net WEBSocket简单例子 推送数据
原创湫化风雨 发布于2018-12-05 10:41:53 阅读数 3214 收藏
展开
asp.net WEBSocket简单例子 推送数据
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);
}
}
————————————————
版权声明:本文为CSDN博主「湫化风雨」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_25702579/article/details/84822704