长链接之websocket在vue的用法
WebSocket是一种在单个TCP连接上进行全双工通信的协议。WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在WebSocket API中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。
1. 什么是websocket
- WebSocket是HTML5下一种新的协议(websocket协议本质上是一个基于tcp的协议)
- Websocket是一个持久化的协议
- 它实现了浏览器与服务器全双工通信,能更好的节省服务器资源和带宽并达到实时通讯的目的
2. 监控连接的状态:WebSocket实例的readyState
- CONNECTING:值为0,表示正在连接。
- OPEN:值为1,表示连接成功,可以通信了。
- CLOSING:值为2,表示连接正在关闭。
- CLOSED:值为3,表示连接已经关闭,或者打开连接失败。
<template>
<div class="app-container">
</div>
</div>
</template>
<script>
export default {
name: 'qrcode',
data() {
return {
path:"ws://127.0.0.1:7878/websocket/",
//一般开发环境http协议使用ws,如果上线到生产需要改为wss协议,wss://127.0.0.1:7878/websocket/
socket:"",
}
},
methods: {
// sokect建立连接
open() {
console.log("socket连接成功")
},
error() {
console.log("连接错误")
},
// 收到socket返回的消息
getMessage (msg) {
console.log("收到消息",msg.data);
sessionStorage.setItem('info',msg.data);
this.close();
this.$router.push('/home');
},
// 发送消息,判断此刻的状态readyState是否为1,再发送
send () {
if (this.socket.readyState===1) {
this.socket.send(this.randomStr)
}
console.log('状态码',this.socket.readyState);
},
// socket关闭
close() {
console.log("socket已经关闭")
},
// 3.初始化websocket
init() {
if(typeof(WebSocket) === "undefined"){
alert("您的浏览器不支持socket")
}else{
// 实例化socket
this.socket = new WebSocket(this.path+this.randomStr)
// 监听socket连接
this.socket.onopen = this.open
// 监听socket错误信息
this.socket.onerror = this.error
// 监听socket消息
this.socket.onmessage = this.getMessage
// 监听socket关闭
this.socket.onclose = this.close
}
},
},
destroyed () {
// 销毁监听
this.socket.onclose = this.close;
},
mounted(){
this.init();
},
created () {
}
};
</script>