Vue中Websocket的使用

2,616 阅读1分钟

一、为什么需要websocket?

前端和后端的交互模式最常见的就是前端发数据请求,从后端拿到数据后展示到页面中。如果前端不做操作,后端不能主动向前端推送数据,这也是http协议的缺陷。

因此,一种新的通信协议应运而生---websocket,他最大的特点就是服务端可以主动向客户端推送消息,客户端也可以主动向服务端发送消息,实现了真正的平等。

1472147-20181112144222661-2039934595.png

websocket其他特点如下:

(1)建立在 TCP 协议之上,服务器端的实现比较容易。

(2)与 HTTP 协议有着良好的兼容性。默认端口也是80和443,并且握手阶段采用 HTTP 协议,因此握手时不容易屏蔽,能通过各种 HTTP 代理服务器。

(3)数据格式比较轻量,性能开销小,通信高效。

(4)可以发送文本,也可以发送二进制数据。

(5)没有同源限制,客户端可以与任意服务器通信。

(6)协议标识符是ws(如果加密,则为wss),服务器网址就是 URL。

二、vue项目如何引用websocket?

vue使用websocket需要注意以下几点:

(1)首先需要判断浏览器是否支持websocket

(2)在组件加载的时候连接websocket,在组件销毁的时候断开websocket

(3)后端接口需要引入socket模块,否则不能实现连接

1472147-20181112144222661-2039934595.png

完整代码<一>:

<template>
    <div>
        <button @click="send">发消息</button>
    </div>
</template>

<script>
export default {
    data () {
        return {
            path:"ws://192.168.0.200:8005/qrCodePage/ID=1/refreshTime=5",
            socket:""
        }
    },
    mounted () {
        // 初始化
        this.init()
    },
    methods: {
        init: function () {
            if(typeof(WebSocket) === "undefined"){
                alert("您的浏览器不支持socket")
            }else{
                // 实例化socket
                this.socket = new WebSocket(this.path)
                // 监听socket连接
                this.socket.onopen = this.open
                // 监听socket错误信息
                this.socket.onerror = this.error
                // 监听socket消息
                this.socket.onmessage = this.getMessage
            }
        },
        open: function () {
            console.log("socket连接成功")
        },
        error: function () {
            console.log("连接错误")
        },
        getMessage: function (msg) {
            console.log(msg.data)
        },
        send: function () {
            this.socket.send(params)
        },
        close: function () {
            console.log("socket已经关闭")
        }
    },
    destroyed () {
        // 销毁监听
        this.socket.onclose = this.close
    }
}
</script>

<style>

</style>

完整代码<二>:

<!DOCTYPE html>
<html lang="en">
 
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Websocket demos</title>
  <script src="https://cdn.bootcss.com/vue/2.5.16/vue.js"></script>
</head>
 
<body>
  <div id="app">
    <input type="text" v-model.trim="msg" @keyup.enter="echo">
    <button @click="echo">发送</button>
  </div>
 
  <script>
    /* global Vue, WebSocket */
    var ws = null
 
    new Vue({
      el: '#app',
      data: {
        msg: ''
      },
      methods: {
        echo: function () {
          if (!this.msg) return
          console.log('WebSocket发送消息: ' + this.msg)
          ws.send(this.msg)
        },
        initWebSocket: function (params) {
          // ws = new WebSocket('wss://echo.websocket.org/')
          ws = new WebSocket("ws://X.X.X.X:9093/websocket");
          // var ws = new WebSocket("ws://localhost:8096/websocket/111405");
          ws.onopen = function (e) {
            console.log('WebSocket已经打开: ')
            console.log(e)
          }
          ws.onmessage = function (e) {
            console.log('WebSocket收到消息: ' + e.data)
          }
          ws.onclose = function (e) {
            console.log('WebSocket关闭: ')
            console.log(e)
          }
          ws.onerror = function (e) {
            console.log('WebSocket发生错误: ')
            console.log(e)
          }
        }
      },
      created: function () {
        this.initWebSocket()
      }
    })
  </script>
</body> 
</html>