后端:C# .net framework 4.8 WebApi
using System; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.WebSockets; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Web; using System.Web.Http; using System.Web.WebSockets; public class WebSocketsController : ApiController { private static List<WebSocket> _sockets = new List<WebSocket>(); [HttpGet, Route("ws")] public HttpResponseMessage GetWs() { if (HttpContext.Current.IsWebSocketRequest) HttpContext.Current.AcceptWebSocketRequest(ProcessRequest); return Request.CreateResponse(HttpStatusCode.SwitchingProtocols); //初次连接切换http协议到websocket } //服务端推送消息测试 int i = 0; [HttpGet, Route("ServerSendTest")] public async Task ServerSendTestAsync() { while (i < 999) { i++; foreach (var innerSocket in _sockets) { if (innerSocket.State == WebSocketState.Open) { var recvBytes = Encoding.UTF8.GetBytes($" | {DateTime.Now:yyyy-MM-ddTHH:mm:ss.fff} | "); ; var sendBuffer = new ArraySegment<byte>(recvBytes); await innerSocket.SendAsync(sendBuffer, WebSocketMessageType.Text, true, CancellationToken.None); } } await Task.Delay(1000); } } //接收客户端消息并处理 private async Task ProcessRequest(AspNetWebSocketContext context) { try { var socket = context.WebSocket;//传入的context中有当前的web socket对象 _sockets.Add(socket);//此处将web socket对象加入一个静态列表中 while (true) { var buffer = new ArraySegment<byte>(new byte[1024]); var receivedResult = await socket.ReceiveAsync(buffer, CancellationToken.None);//对web socket进行异步接收数据 if (receivedResult.MessageType == WebSocketMessageType.Close) { await socket.CloseAsync(WebSocketCloseStatus.Empty, string.Empty, CancellationToken.None);//如果client发起close请求,对client进行ack _sockets.Remove(socket); break; } if (socket.State == System.Net.WebSockets.WebSocketState.Open) { string recvMsg = Encoding.UTF8.GetString(buffer.Array, 0, receivedResult.Count); var recvBytes = Encoding.UTF8.GetBytes(recvMsg + $" OK | {DateTime.Now:yyyy-MM-ddTHH:mm:ss.fff}"); ; var sendBuffer = new ArraySegment<byte>(recvBytes); foreach (var innerSocket in _sockets) { //当接收到文本消息时,对当前服务器上所有web socket连接进行广播 if (innerSocket != socket) { await innerSocket.SendAsync(sendBuffer, WebSocketMessageType.Text, true, CancellationToken.None); } } } } } catch { } } }
前端测试:MS-edge , JS
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title></title> <script type="text/javascript" src="jquery-3.6.0.min.js"></script> <style type="text/css"> table { padding: 0; margin: 0; border-collapse: collapse; } td { border: 1px solid #009999; padding: 6px 6px 6px 12px; color: #4f6b72; text-align: center; } input { font-size: 15pt; } </style> <script type="text/javascript"> function websocket() { var ws = new WebSocket("ws://localhost:54924/ws"); ws.onopen = function () { console.log("open"); ws.send("hello"); }; ws.onmessage = function (evt) { console.log(evt.data); $("#thtil").text(evt.data); }; ws.onclose = function (evt) { console.log("WebSocketClosed!"); }; ws.onerror = function (evt) { console.log("WebSocketError!"); }; } </script> </head> <body> <span style="font-size:30pt">WebSocket Test</span><p /> <input type="button" id="QueryButton1" value="WebSocket Test" onclick="websocket();" /> <br /><br /> <span id="thtil"></span><p /> <div id="dataDiv"> </div> </body> </html>
标签:WebApi,donet,websocket,socket,System,innerSocket,ws,var,using From: https://www.cnblogs.com/leavind/p/16715859.html