Vue中实现WEBSOCKET前后端通讯

前言:什么是WebSocket?
WebSocket和http一样,都是一种网络传输协议,但是和Http协议相比,它有一点不同,它可以在单个TCP连接上进行全双工通信,通俗来说就是客户端可以向服务端发送请求,服务端也可以向客户端发送请求;总的来说:http协议服务端响应到客户端是被动的,而webSocket协议服务端请求到客户端是主动的。
这张图网上有很多,完美展示了http和webSocket的区别:
在这里插入图片描述

  1. 在Vue项目中安装WebSocket库
//npm install --save websocket
npm install --save vue-native-websocket
  1. main.js全局配置
import websocket from 'vue-native-websocket';
Vue.use(websocket, '', {
    connectManually: true, // 手动连接
    format: 'json', // json格式
    reconnection: true, // 是否自动重连
    reconnectionAttempts: 5, // 自动重连次数
    reconnectionDelay: 2000, // 重连间隔时间
});
  1. 创建WebSocket连接
export default {
  data() {
    return {
      socket:null,
      WS:{
        wsCount:0
       }
    }
  },
  mounted() {
    this.initWebSocket()
  },
  created() {
  	
  },
  destroyed() {
    if(this.socket){
      this.socket.close() //离开路由之后断开websocket连接
       console.log('socket关闭1')
     }
  },
  methods: {
    initWebSocket() {
      if (typeof WebSocket === "undefined") {
        alert("您的浏览器不支持socket");
      } else {
        let WSUrl = ‘ws://10.0.0.121:8700/camera/ws’;
        // 实例化socket
        this.socket = new WebSocket(`${WSUrl}`);
        // 监听socket连接
        this.socket.onopen = this.open;
        // 监听socket错误信息
        this.socket.onerror = this.error;
        // 监听socket消息
        this.socket.onmessage = this.getMessage;
        this.socket.onsend = this.send;
        // 关闭cocket
        this.socket.onclose = this.close;
      }
    },
    open() {
      //连接建立之后执行send方法发送数据
      this.socket.send(JSON.stringify({"app": "start"}));
      console.log("socket连接成功");
    },
    error() {
      //连接建立失败重连
      console.log("连接错误");
      this.socket = null;
      const timer = setTimeout(() => {
        this.initWebSocket();
        this.WS.wsCount++;
      }, 5000);
      if (this.WS.wsCount > 4) {
        clearTimeout(timer);
      }
    },
    getMessage(msg) {
      //数据接收
      console.log(JSON.parse(msg.data));
    },
    send(Data) {
      console.log('数据发送')
	  //数据发送
	  this.socket.send(Data)
    },
    close() {
      console.log("socket已经关闭");
    },
  }
}
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Vue实现WebSocket需要以下步骤: 1. 创建WebSocket对象 在Vue,可以在`created()`钩子函数创建WebSocket对象,如下所示: ``` created() { this.websocket = new WebSocket('ws://localhost:8080'); } ``` 在这里,我们创建了一个WebSocket对象,并指定了WebSocket服务器的地址。 2. 监听WebSocket事件 WebSocket对象有一些事件,比如`open`、`message`、`error`、`close`等。在Vue,可以在`created()`钩子函数WebSocket对象添加事件监听器,如下所示: ``` created() { this.websocket = new WebSocket('ws://localhost:8080'); this.websocket.onopen = () => { console.log('WebSocket连接已打开!'); }; this.websocket.onmessage = (event) => { console.log('收到来自服务器的消息:', event.data); }; this.websocket.onerror = () => { console.error('WebSocket连接发生错误!'); }; this.websocket.onclose = () => { console.log('WebSocket连接已关闭!'); }; } ``` 在这里,我们添加了`open`、`message`、`error`、`close`事件的监听器,分别用于处理WebSocket连接建立、收到服务器消息、连接错误、连接关闭等情况。 3. 发送消息到WebSocket服务器 在Vue,可以使用`this.websocket.send()`方法向WebSocket服务器发送消息,如下所示: ``` methods: { sendMessage() { this.websocket.send('Hello, WebSocket!'); } } ``` 在这里,我们定义了一个`sendMessage()`方法,在方法调用`this.websocket.send()`方法向WebSocket服务器发送消息。 以上就是Vue实现WebSocket的基本步骤。注意,在使用WebSocket时,需要注意浏览器的安全策略,确保WebSocket服务器的地址与Vue应用的地址在同一域名下。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值