- 官网
- 代码
// 为了浏览器兼容websocket
const WebSocket = window.WebSocket || window.MozWebSocket
// 创建连接
this.socket = new WebSocket('ws://xxx')
// 连接成功
this.socket.onopen = (res)=>{
console.log('websocket 连接成功')
this.socket.send('入参字段') // 传递的参数字段
}
// 后端针对刚才传的字段返回对应数据
this.socket.onmessage = e=>{
console.log(e.data,'从服务器获取的数据')
//关闭连接
this.socket.close()
}
// 连接失败后的回调函数
this.socket.onerror = function (err) {
console.log("连接失败了",err);
};
- 前端写websocket请求时为什么要这样定义const WebSocket = window.WebSocket || window.MozWebSocket?




![[Android 四大组件] --- Activity](https://img-blog.csdnimg.cn/ed7722f2e08749dfade6a1b618b9ec16.png)




![[集创赛海云捷讯杯]全国二等奖经验分享](https://img-blog.csdnimg.cn/9ccaae55ba57441b8cfc0a068f484816.png)


![国民八路参考文献:[8]许少辉.乡村振兴战略下传统村落文化旅游设计[M]北京:中国建筑工业出版社,2022.](https://img-blog.csdnimg.cn/e56ee9e8456942778a703249ec8cf673.jpeg#pic_center)






