- 官网
- 代码
// 为了浏览器兼容websocketconst WebSocket = window.WebSocket || window.MozWebSocket
// 创建连接 this.socket =newWebSocket('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?
报错
Uncaught DOMException: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state. at socket.onopen
const WebSocket = window.WebSocket || window.MozWebSocket
this.socket =newWebSocket(this.$webSocketUrl)this.socket.onopen=()=>{
console.log(WebSocket.OPEN,'WebSocket.OPEN')if(this.socket &&this.socket.readyState === WebSocket.OPEN){
console.log('open2')this.socket.send(`xxxx`)}else{
console.error('Cannot send data, WebSocket is not open');}}
本文转载自: https://blog.csdn.net/m0_45011929/article/details/132559235
版权归原作者 禾苗种树 所有, 如有侵权,请联系我们删除。
版权归原作者 禾苗种树 所有, 如有侵权,请联系我们删除。