private async Task Handle(HttpContext context, WebsocketClient webSocket, IConfigService configService) { var buffer = new byte[1024 * 2]; WebSocketReceiveResult result = null; do { result = await webSocket.Client.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None); webSocket.LastHeartbeatTime = DateTime.Now; var message = await ConvertWebsocketMessage(result, buffer); if (message == "ping") { //如果是ping,回复本地数据的md5版本 var appId = context.Request.Headers["appid"]; var md5 = await configService.AppPublishedConfigsMd5Cache(appId); var md5Data = Encoding.UTF8.GetBytes($"V:{md5}"); await webSocket.Client.SendAsync(new ArraySegment <byte>(md5Data, 0, md5Data.Length), WebSocketMessageType.Text, true, CancellationToken.None); } else { //如果不是心跳消息,回复0 var zeroData = Encoding.UTF8.GetBytes("0"); await webSocket.Client.SendAsync(new ArraySegment <byte>(zeroData, 0, zeroData.Length), WebSocketMessageType.Text, true, CancellationToken.None); } }while (!result.CloseStatus.HasValue); _logger.LogInformation($"Websocket close , closeStatus:{result.CloseStatus} closeDesc:{result.CloseStatusDescription}"); await _websocketCollection.RemoveClient(webSocket, result.CloseStatus, result.CloseStatusDescription); }
private async Task Handle(HttpContext context, WebsocketClient socketClient, IConfigService configService) { var buffer = new byte[1024 * 2]; WebSocketReceiveResult result = null; do { result = await socketClient.Client.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None); socketClient.LastHeartbeatTime = DateTime.Now; var message = await ReadWebsocketMessage(result, buffer); if (message == "ping") { //如果是ping,回复本地数据的md5版本 var appId = context.Request.Headers["appid"]; var md5 = await configService.AppPublishedConfigsMd5CacheWithInheritanced(appId); await SendMessage(socketClient.Client, $"V:{md5}"); } else { //如果不是心跳消息,回复0 await SendMessage(socketClient.Client, "0"); } }while (!result.CloseStatus.HasValue); _logger.LogInformation($"Websocket close , closeStatus:{result.CloseStatus} closeDesc:{result.CloseStatusDescription}"); await _websocketCollection.RemoveClient(socketClient, result.CloseStatus, result.CloseStatusDescription); }
public void AddClient(WebsocketClient client) { lock (_lockObj) { client.LastHeartbeatTime = DateTime.Now; Clients.Add(client); } }
public async Task SendMessageToOne(WebsocketClient client, string message) { if (client.Client.State == WebSocketState.Open) { var data = Encoding.UTF8.GetBytes(message); await client.Client.SendAsync(new ArraySegment <byte>(data, 0, data.Length), WebSocketMessageType.Text, true, CancellationToken.None); } }
public async Task RemoveClient(WebsocketClient client, WebSocketCloseStatus?closeStatus, string closeDesc = null) { if (_Clients.TryRemove(client.Id, out WebsocketClient tryRemoveClient) && client.Client.State == WebSocketState.Open) { await client.Client.CloseAsync(closeStatus.HasValue?closeStatus.Value : WebSocketCloseStatus.Empty, closeDesc, CancellationToken.None); client.Client.Dispose(); } }
public async Task SendActionToOne(WebsocketClient client, WebsocketAction action) { if (client.Client.State == WebSocketState.Open) { var json = JsonConvert.SerializeObject(action); var data = Encoding.UTF8.GetBytes(json); await client.Client.SendAsync(new ArraySegment <byte>(data, 0, data.Length), WebSocketMessageType.Text, true, CancellationToken.None); } }
public async Task RemoveClient(WebsocketClient client, WebSocketCloseStatus?closeStatus, string closeDesc = null) { lock (_lockObj) { Clients.Remove(client); } if (client.Client.State == WebSocketState.Open) { await client.Client.CloseAsync(closeStatus.HasValue?closeStatus.Value : WebSocketCloseStatus.Empty, closeDesc, CancellationToken.None); client.Client.Dispose(); } }
public async Task Invoke(HttpContext context, IAppBasicAuthService appBasicAuth, IConfigService configService) { if (context.Request.Path == "/ws") { if (context.WebSockets.IsWebSocketRequest) { if (!await appBasicAuth.ValidAsync(context.Request)) { await context.Response.WriteAsync("basic auth failed ."); return; } var appId = context.Request.Headers["appid"]; if (string.IsNullOrEmpty(appId)) { var appIdSecret = appBasicAuth.GetAppIdSecret(context.Request); appId = appIdSecret.Item1; } WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync(); var client = new WebsocketClient() { Client = webSocket, Id = Guid.NewGuid().ToString(), AppId = appId, LastHeartbeatTime = DateTime.Now }; _websocketCollection.AddClient(client); _logger.LogInformation("Websocket client {0} Added ", client.Id); try { await Handle(context, client, configService); } catch (Exception ex) { _logger.LogError(ex, "Handle websocket client {0} err .", client.Id); await _websocketCollection.RemoveClient(client, WebSocketCloseStatus.Empty, ex.Message); await context.Response.WriteAsync("closed"); } } else { context.Response.StatusCode = 400; } } else { await _next(context); } }
public async Task Invoke(HttpContext context, IAppService appService, IConfigService configService) { if (context.Request.Path == "/ws") { if (context.WebSockets.IsWebSocketRequest) { var basicAuth = new BasicAuthenticationAttribute(appService); if (!await basicAuth.Valid(context.Request)) { await context.Response.WriteAsync("closed"); return; } var appId = context.Request.Headers["appid"]; WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync(); var client = new WebsocketClient() { Client = webSocket, Id = Guid.NewGuid().ToString(), AppId = appId }; _websocketCollection.AddClient(client); _logger.LogInformation("Websocket client {0} Added ", client.Id); try { await Handle(context, client, configService); } catch (Exception ex) { _logger.LogError(ex, "Handle websocket client {0} err .", client.Id); await _websocketCollection.RemoveClient(client, WebSocketCloseStatus.Empty, ex.Message); await context.Response.WriteAsync("closed"); } } else { context.Response.StatusCode = 400; } } else { await _next(context); } }
public void AddClient(WebsocketClient client) { _Clients.TryAdd(client.Id, client); }
public async Task Invoke(HttpContext context, IAppBasicAuthService appBasicAuth, IConfigService configService) { if (context.Request.Path == "/ws") { if (context.WebSockets.IsWebSocketRequest) { if (!await appBasicAuth.ValidAsync(context.Request)) { context.Response.StatusCode = 401; await context.Response.WriteAsync("basic auth failed ."); return; } var appId = context.Request.Headers["appid"]; if (string.IsNullOrEmpty(appId)) { var appIdSecret = appBasicAuth.GetAppIdSecret(context.Request); appId = appIdSecret.Item1; } context.Request.Query.TryGetValue("client_name", out StringValues name); if (!string.IsNullOrEmpty(name)) { name = HttpUtility.UrlDecode(name); } else { _logger.LogInformation("Websocket client request No Name property "); } context.Request.Query.TryGetValue("client_tag", out StringValues tag); if (!string.IsNullOrEmpty(tag)) { tag = HttpUtility.UrlDecode(tag); } else { _logger.LogInformation("Websocket client request No TAG property "); } WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync(); var clientIp = GetRemoteIp(context.Request); var client = new WebsocketClient() { Client = webSocket, Id = Guid.NewGuid().ToString(), AppId = appId, LastHeartbeatTime = DateTime.Now, Name = name, Tag = tag, Ip = clientIp.ToString() }; _websocketCollection.AddClient(client); _logger.LogInformation("Websocket client {0} Added ", client.Id); try { await Handle(context, client, configService); } catch (Exception ex) { _logger.LogError(ex, "Handle websocket client {0} err .", client.Id); await _websocketCollection.RemoveClient(client, WebSocketCloseStatus.Empty, ex.Message); context.Response.StatusCode = 500; await context.Response.WriteAsync("closed"); } } else { context.Response.StatusCode = 400; } } else { await _next(context); } }