很简单就不写太多介绍了,仅展示服务端代码!!
Configure
在Startup
类的方法中添加WebSockets中间件
app.UseWebSockets();
可以配置以下设置:
KeepAliveInterval
多久发送一次“ ping”帧到客户端,以确保代理保持连接打开。默认值为两分钟。
ReceiveBufferSize 用于接收数据的缓冲区的大小。高级用户可能需要根据数据大小更改此项以进行性能调整。默认值为4 KB。
var webSocketOptions = new WebSocketOptions() { KeepAliveInterval = TimeSpan.FromSeconds(120), ReceiveBufferSize = 200 * 1024 }; app.UseWebSockets(webSocketOptions);
增加一个socket帮助类库
SocketHandler
public class SocketHandler { public const int BufferSize = 4096; public string basestringjson = string.Empty; WebSocket socket; SocketHandler(WebSocket socket) { this.socket = socket; } async Task EchoLoop() { var buffer = new byte[BufferSize]; //代码接收消息并立即发回相同的消息。 循环发送和接收消息,直到客户端关闭连接 WebSocketReceiveResult result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None); while (!result.CloseStatus.HasValue) { await socket.SendAsync(new ArraySegment<byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None); result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None); } await socket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None); } static async Task Acceptor(HttpContext hc, Func<Task> n) { if (!hc.WebSockets.IsWebSocketRequest) return; var socket = await hc.WebSockets.AcceptWebSocketAsync();//将请求转换为WebSocket var h = new SocketHandler(socket); await h.EchoLoop(); } /// <summary> /// branches the request pipeline for this SocketHandler usage /// </summary> /// <param name="app"></param> public static void Map(IApplicationBuilder app) { app.UseWebSockets(); app.Use(SocketHandler.Acceptor); } }
最后在startup.cs中调用,最终代码:
var webSocketOptions = new WebSocketOptions() { KeepAliveInterval = TimeSpan.FromSeconds(120), ReceiveBufferSize = 200 * 1024 }; app.UseWebSockets(webSocketOptions); app.Map("/socketname", SocketHandler.Map);
socketname与客户端建立连接名相同即可