前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >dotnet core使用websocket通信

dotnet core使用websocket通信

作者头像
sofu456
发布2021-03-20 13:59:30
9360
发布2021-03-20 13:59:30
举报
文章被收录于专栏:sofu456

dotnet core5.0

dotnet core支持websocket通信配置如下

app.UseWebSockets(new WebSocketOptions() {KeepAliveInterval=TimeSpan.FromSeconds(120)});

相关配置可以在msdn上查到,建立websocket服务端如下,代码不能放在设置mvc模式后面,否则接收的js端的数据会被mvc过滤

代码语言:javascript
复制
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();
    }
});

js客户端

this.websock = new WebSocket( ‘ws://’ + window.location.host + ‘/ws’ ); websocket连接打开事件onopen、接收数据事件onmessage

http 101

socketjs-node upgrade请求,请求升级服务端websocket,否则客户端接收不到数据

在这里插入图片描述
在这里插入图片描述

websocket version 13,websocket各个浏览器版本不同,需要兼容低版本浏览器 onopen后,一直未收到onmessage消息,开始以为是http 101错误,后面查了很久才发现,SendAsync函数中有一个endofmessage参数,置为true才发送一个完整的包,否则一直缓存

handshake Sec-WebSocket-Protocol non empty

js端创建websocket的时候第二个参数protocols非空,如下

this.socket = new WebSocket(this.url, this.options.protocols || null);

服务端需要创建子协议返回数据,去掉protocols会比较简单

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021/03/03 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • dotnet core5.0
  • js客户端
  • http 101
  • handshake Sec-WebSocket-Protocol non empty
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档