前端建立WebSocket

建立,new一个

this.wSocket = new WebSocket('ws://192.xx.xx.xx:8080/xxx/xxxx');
 if (!this.wSocket) {
    console.log('您的浏览器不支持websocket协议!');
    return;
 }

PS:若是https环境,将ws改为wss即可
俩个函数接收与发送

this.wSocket.onopen = () => {
   console.log('websocket已链接.');
};
 this.wSocket.onmessage = (e) => {
   console.log('e就是返回的数据');
   // 在这里写处理函数
};
this.wSocket.send(xxxxx); // 向后端发送数据

当想关闭时

this.wSocket.close();
this.wSocket.onclose = () => {
   console.log('websocket连接已关闭...');
 };
发布了25 篇原创文章 · 获赞 7 · 访问量 9211

猜你喜欢

转载自blog.csdn.net/Beth__hui/article/details/103405923