简介:websocket是一个浏览器和服务器之间双向数据传输的协议;
可以使服务器避免打开多个http连接进行工作
目前支持两种统一资源标识符:ws , wss
websocket连接请求,服务器发出响应,这个过程称为握手,握手的过程只需要一次,就可以实现持久连接
浏览器中内置了websocket,无需引入直接使用
data() {
return {
url: 'ws://123.207.136.134:9010/ajaxchattest',//要连接的websocket地址
webSocket: null,
status: '',
form: { message: null },
}
},
created() {
this.init()
},
destroyed() {
this.webSocket.close()
},
methods: {
submit() {
this.$refs['form'].validate((valid) => {
if (valid) {
this.send(this.form.message)
} else {
return false
}
})
},
init() {
const wsuri = this.url
this.webSocket = new WebSocket(wsuri)
this.webSocket.onmessage = this.onmessage
this.webSocket.onopen = this.onopen
this.webSocket.onerror = this.onerror
this.webSocket.onclose = this.onclose
},
onopen() {
this.status = '成功'
},
one rror() {
this.status = '失败'
this.initWebSocket()
},
onmessage({ data }) {
//截掉测试webSocket地址广告
this.data.push(data.substring(0, data.length - 66))
},
send(Data) {
this.webSocket.send(Data)
},
onclose(e) {
this.status = '断开'
},
},