dotnet core支持websocket通信配置如下
app.UseWebSockets(new WebSocketOptions() {KeepAliveInterval=TimeSpan.FromSeconds(120)});
相关配置可以在msdn上查到,建立websocket服务端如下,代码不能放在设置mvc模式后面,否则接收的js端的数据会被mvc过滤
app.Use(async (context, next) =>{
if (context.Request.Path == "/ws"){
if (context.WebSockets.IsWebSocketRequest){
using (WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync()){
await WsData.BroadCastData(webSocket,context);
}
}
else{
await next();
}
}
else{
await next();
}
});
this.websock = new WebSocket( ‘ws://’ + window.location.host + ‘/ws’ ); websocket连接打开事件onopen、接收数据事件onmessage
socketjs-node upgrade请求,请求升级服务端websocket,否则客户端接收不到数据
websocket version 13,websocket各个浏览器版本不同,需要兼容低版本浏览器 onopen后,一直未收到onmessage消息,开始以为是http 101错误,后面查了很久才发现,SendAsync函数中有一个endofmessage参数,置为true才发送一个完整的包,否则一直缓存
js端创建websocket的时候第二个参数protocols非空,如下
this.socket = new WebSocket(this.url, this.options.protocols || null);
服务端需要创建子协议返回数据,去掉protocols会比较简单
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有