websocket + vue

websocket + vue,第1张

export default { name: 'Resource', data () {return { wsUrl: '', websocket:null} }, methods: {updateUrl(urlPath){ let _this = this if (urlPath.indexOf('sockjs') != -1) {_this.wsUrl = 'http://' + CONFIG.WEBSOCKET_URL + urlPath + "" + _this.userData.user } else {if (window.location.protocol == 'http:') { _this.wsUrl = 'ws://' + CONFIG.WEBSOCKET_URL + urlPath + "" + _this.userData.user }else { _this.wsUrl = 'wss://' + CONFIG.WEBSOCKET_URL + urlPath + "" + _this.userData.user } }},webSocketLink(){ let _this = this var heartCheck = {timeout: 5000,//5秒timeoutObj: null,reset: function(){ clearInterval(this.timeoutObj) return this },start: function(){ this.timeoutObj = setInterval(function(){_this.websocket.send("HeartBeat") console.log("HeartBeat") }, this.timeout)} } if ('WebSocket' in window) {_this.updateUrl("/webSocketServer") _this.websocket = new WebSocket(_this.wsUrl) } else if ('MozWebSocket' in window) {_this.updateUrl("/webSocketServer") _this.websocket = new MozWebSocket(_this.wsUrl) } else {_this.updateUrl("/sockjs/webSocketServer") _this.websocket = new SockJS(_this.wsUrl) } _this.websocket.onopen = function(){console.log("websock连接成功") heartCheck.reset().start() } _this.websocket.onmessage = function (event) {console.log(event.data) }} }, beforeRouteLeave (to, from, next) {if(this.websocket){ this.websocket.close()} }, created(){this.webSocketLink() }}</script>

链接:https://www.jianshu.com/p/ab47f613e8c6

首先写一个公共方法 socket.js

functiongetSocket(url, params, callback) {

  let socket

  if(typeof(WebSocket) === 'undefined') {

    console.log('您的浏览器不支持WebSocket')

  } else{

    console.log('您的浏览器支持WebSocket')

    // 初始化 WebSocket 对象,指定要连接的服务器地址与端口建立连接

    socket = newWebSocket(url)

    // 打开事件

    socket.onopen = function() {

      console.log('Socket 已打开')

      socket.send(params)

    }

    // 获得消息事件

    socket.onmessage = function(msg) {

      // 发现消息进入, 开始处理前端触发逻辑

      callback(msg, socket)

    }

    // 关闭事件

    socket.onclose = function() {

      console.log('Socket 已关闭')

    }

    // 发生了错误事件

    socket.onerror = function() {

      console.log('Socket 发生了错误,请刷新页面')

      // 此时可以尝试刷新页面

    }

  }

}

export {

  getSocket

}

使用

test.vue

<script>

import {getSocket} from '@/utils/socket.js'

export default{

  data() {

    return{

      wsData: {}, // 保存 websocket 数据对象

      form: { // 表单

        name: '',

        age: ''

      }

    }

  },

  beforeDestroy() {

    this.wsData.close()// 关闭 websocket

  },

  created() {

    this.getSocketData()

  },

  methods: {

    // 获取数据

    getSocketData() {

      let params = this.form

      getSocket(

        `ws://path`,

        JSON.stringify(params),

        (data, ws) =>{

          console.log(data, ws)

          // 保存数据对象, 以便发送消息

          this.wsData = ws

        }

      )

    },

    // 发送数据

    sendSocketData() {

      let params = this.form

      params.name = 'xx'

      params.age= '18'

      this.wsData.send(JSON.stringify(params))

    }

  }

}

</script>

vue跨域解决方法

使用axios请求

第一步骤

在vue.config.js 文件中 module.exports = { } 中添加

devServer: {

proxy: {

'/profile': { //指定 路径 要 跨域请求地址

// 在本地会创建一个虚拟服务端,然后发送请求的数据,并同时接收请求的数据,这样服务端和服务端进行数据的交互就不会有跨域问题

// 将/api开头的url转发到target上。

target: ' https://sso.www.eee.cn/profile',// 跨域请求地址

changeOrigin: true, //虚拟的站点需要更管origin

ws: true, // 代理websockets

secure: true, // 如果是https接口,需要配置这个参数

pathRewrite: {

// 顾名思义,将/api重写为 / 此时url变为 http://192.168.101.110:8888/ 而不是 http://192.168.101.110:8888/api

'^/profile': ''

}

}

}

第二步骤

在封装axios请求中设置

const service = axios.create({

baseURL: '/profile',//定义要跨域的接口路径

withCredentials: true,//是否支持跨域

timeout: 500000, // request timeout

headers: {

'Cache-Control': 'no-cache',

'Content-Type': 'application/x-www-form-urlencoded'

}

})


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/bake/11759088.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-18
下一篇 2023-05-18

发表评论

登录后才能评论

评论列表(0条)

保存