vue项目使用websocket技术

  

一、为什么需要 websocket?

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

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

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 模块,否则不能实现连接

 

不废话了,直接附上完整代码:

 

<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>

 

更多前端资料关注【凤凰城下的小码农】,回复【电子书】免费领取

 

 

 

欢迎关注我的开源项目,react-admin-plus,欢迎 star

我的个人主页,地址