前端使用webscoket

前端

<template>
  <div class="wrap">
    <button @click="socketEmit">连接Socket</button>
    <button @click="socketSendmsg">发送数据</button>
  </div>
</template>

<script>
export default {
  data(){
    return {
      randomId:null,
    }
  },
  methods:{
    socketEmit(){
      // 开始连接 socket
      this.$socket.open();
      // 订阅事件,testCall 是与后端约定好的名称
      this.sockets.subscribe('testCall', (res) => {
        if(res.code == 200 && res.randomId === this.randomId){
          console.log('召唤成功')

        }
      })
    },
    // 发送消息
    socketSendmsg(){
      this.randomId = Math.random();
      // testCall 是与后端约定好的名称
      this.$socket.emit('testCall', {
        "randomId": this.randomId,
        "deviceId": "123456"
      });
    },
  },
  sockets: {
    connect: function () {
      console.log('连接成功')
    },
    disconnect: function () {
      console.log('断开连接')
    },
    reconnect: function () {
      console.log('重新连接')
    },
  },
  beforeDestroy(){
    // 关闭 Socket
    this.sockets.unsubscribe('testCall');
    this.$socket.close();
  },
}
</script>

main.js

import VueSocketIO from 'vue-socket.io'

Vue.use(new VueSocketIO({
  // 生产环境建议关闭,开发环境打开(在控制台看到socket连接和事件监听的信息)
  debug: true,
  connection:'http://metinseylan.com:1992',
  options:{
    // 创建时是否自动连接 我们这里设定为false,在指定页面再开启
    autoConnect: false,
    // 路径(默认值:/socket.io/)
    path: "/my-app/",
    // 目前有两种传输方式:HTTP long-polling(可简称:polling)、WebSocket
    transports: ['polling'],
    // 附加请求头(在服务器端的 socket.handshake.headers 对象中找到)
    extraHeaders:{},
  },
}))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CongJiYong

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值