网站建设赚钱吗排版设计是什么工作
news/
2025/9/29 14:27:17/
文章来源:
网站建设赚钱吗,排版设计是什么工作,广州网站设计公司济南兴田德润o简介图片,嵌入式软件开发工程师是做什么的基于WebSocket实现的后台服务#xff0c;用于接收客户端的心跳消息#xff0c;并根据心跳消息来维护客户端连接。
具体实现中#xff0c;服务启动后会创建一个HttpListener对象#xff0c;用于监听客户端的WebSocket连接请求。当客户端连接成功后#xff0c;服务会为每个…基于WebSocket实现的后台服务用于接收客户端的心跳消息并根据心跳消息来维护客户端连接。
具体实现中服务启动后会创建一个HttpListener对象用于监听客户端的WebSocket连接请求。当客户端连接成功后服务会为每个连接创建一个Task实例用于接收客户端发送的心跳消息并根据心跳消息更新心跳时间戳。服务还会定期向客户端发送心跳消息以保持连接的活跃状态。
如果服务在一定时间内没有收到客户端发送的心跳消息就会认为客户端已经掉线服务会关闭连接并从连接列表中移除该客户端。
此服务适用于需要实现长连接的场景例如实时消息推送、在线游戏等。需要注意的是此服务只能用于WebSocket通信客户端必须实现WebSocket协议。
using Microsoft.Extensions.Hosting;
using MSEBP.Kernel.Common.Logging;
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;namespace Authorization.WebApi
{/// summary/// 此代码只能用于 websocket通信,客户端必须websocket实现暂时无用。/// /summarypublic class WebSocketBackgroundService : IHostedService, IDisposable{private const int _heartBeatInterval 30000; // 心跳间隔毫秒private const int _heartBeatTimeout 60000; // 心跳超时时间毫秒private const int _clientIdLength 10;private readonly CancellationTokenSource _cts new CancellationTokenSource();private readonly ConcurrentDictionarystring, WebSocket _clients new ConcurrentDictionarystring, WebSocket();private readonly ILogger _logger;/// summary/// /// /summary/// param namelogger/parampublic WebSocketBackgroundService(ILogger logger){_logger logger;}/// summary/// /// /summary/// param namecancellationToken/param/// returns/returnspublic async Task StartAsync(CancellationToken cancellationToken){IPAddress localIp Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault(ip ip.AddressFamily AddressFamily.InterNetwork);if (localIp null){throw new Exception(Cannot find local IP address.);}IPEndPoint localEndPoint new IPEndPoint(localIp, 8181);HttpListener listener new HttpListener();//listener.Prefixes.Add($http://{localEndPoint}/);listener.Start();_ Task.Run(async () {try{while (!_cts.IsCancellationRequested){HttpListenerContext context await listener.GetContextAsync();if (context.Request.IsWebSocketRequest){WebSocket webSocket await AcceptWebSocketAsync(context);_ Task.Run(async () {await ReceiveHeartbeatAsync(webSocket);}, _cts.Token);}else{context.Response.StatusCode 400;context.Response.Close();}}}catch (Exception ex){_logger.Error(ex, WebSocket server error.);}}, _cts.Token);}private async TaskWebSocket AcceptWebSocketAsync(HttpListenerContext context){HttpListenerWebSocketContext wsContext await context.AcceptWebSocketAsync(null);WebSocket webSocket wsContext.WebSocket;return webSocket;}private async Task ReceiveHeartbeatAsync(WebSocket webSocket){byte[] buffer new byte[1024];CancellationToken token _cts.Token;DateTime lastHeartbeatTime DateTime.UtcNow;try{while (webSocket.State WebSocketState.Open !token.IsCancellationRequested){WebSocketReceiveResult result await webSocket.ReceiveAsync(new ArraySegmentbyte(buffer), CancellationToken.None);if (result.CloseStatus.HasValue){await CloseWebSocketAsync(webSocket, result.CloseStatus.Value, result.CloseStatusDescription);break;}else if (result.MessageType WebSocketMessageType.Text){string message Encoding.UTF8.GetString(buffer, 0, result.Count).Trim();if (message.StartsWith(heartbeat)){lastHeartbeatTime DateTime.UtcNow;string clientId message.Substring(0, Math.Min(message.Length, _clientIdLength));_clients.TryAdd(clientId, webSocket);}else if (string.IsNullOrEmpty(message)){await CloseWebSocketAsync(webSocket, WebSocketCloseStatus.NormalClosure, Closed by client);break;}else{// 处理业务逻辑}}// 检测心跳超时if ((DateTime.UtcNow - lastHeartbeatTime).TotalMilliseconds _heartBeatTimeout) { await CloseWebSocketAsync(webSocket, WebSocketCloseStatus.NormalClosure, Heartbeat timeout);break;}}}catch (WebSocketException ex) when (ex.WebSocketErrorCode WebSocketError.ConnectionClosedPrematurely){// WebSocket 连接被意外关闭忽略异常}catch (Exception ex){_logger.Error(ex, WebSocket error.);}finally{// 移除客户端连接foreach (var item in _clients){if (item.Value webSocket){_clients.TryRemove(item.Key, out _);break;}}await CloseWebSocketAsync(webSocket, WebSocketCloseStatus.NormalClosure, Closed by server);}}private async Task CloseWebSocketAsync(WebSocket webSocket, WebSocketCloseStatus closeStatus, string closeStatusDescription){try{await webSocket.CloseAsync(closeStatus, closeStatusDescription, CancellationToken.None);}catch (WebSocketException ex) when (ex.WebSocketErrorCode WebSocketError.ConnectionClosedPrematurely){// WebSocket 连接已经关闭忽略异常}catch (Exception ex){_logger.Error(ex, Failed to close WebSocket.);}}public async Task StopAsync(CancellationToken cancellationToken){_cts.Cancel();await Task.CompletedTask;}public void Dispose(){_cts.Dispose();}}
}
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/921893.shtml
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!