<template>
<button type="button" v-on:click="sendMQMessage">发送</button>
</template>
<script>
import $ from 'jquery';
import axios from 'axios';
import qs from 'qs';
import Cookies from 'js-cookie';
export default {
name: 'webSocket',
props: {},
data: function() {
return {
sendMessageContent: '你好啊WebSocket!',
userNumber: '',
token: '',
webSocketHandle: null,
};
},
created() {
let user = Cookies.get('user');
let token = Cookies.get('token');
let userNumber = Cookies.get('userName');
this.userNumber = userNumber;
this.token = token;
//初始化webSocket
this.initWebSocket();
},
destroyed() {
//销毁webSocket
this.destroyWebSocket();
},
methods: {
// 发送MQ的消息
sendMQMessageJSON: function() {
try {
let data = {
message: this.sendMessageContent,
userNumber: this.userNumber,
token: this.token
};
data = JSON.stringify(data);
let contentType = 'application/json;charset=utf-8';
console.log('发送请求......');
axios.post(url, data, {
headers: {
'Content-Type': contentType
}
})
.catch(function(error) {
console.log(error.message);
})
.then(function(response) {
console.log(response.data);
});
} catch (e) {
console.log(e);
}
},
// 开始接受MQ的消息
startAccetpMQMessage: function() {
try {
this.destroyWebSocket();
this.webSocketHandle = null;
this.initWebSocket();
} catch (e) {
console.log('开始连接出错。');
console.log(e);
}
},
sendMessageByWebSocket: function(message) {
try {
this.webSocketHandle.send(message);
} catch (e) {
console.log('发送消息出错。');
console.log(e);
if (!this.webSocketHandle.isActive()) {
this.startAccetpMQMessage();
}
}
},
// 初始化webSocket操作句柄
initWebSocket: function() {
try {
const wsurl = this.urlWS + this.userNumber + '?token=' + this.token;
this.webSocketHandle = new WebSocket(wsurl);
this.webSocketHandle.onmessage = this.websocketOnMessage;
} catch (e) {
console.log('初始连接出错。');
console.log(e);
}
},
//返回的信息在result里
websocketOnMessage: function(result) {
try {
//输出收到的消息
console.log(result);
} catch (e) {
console.log('收到消息出错。');
console.log(e);
}
},
websocketOnOpen: function() {
try {
let actions = { message: 'hello websocket!' };
this.sendMessageByWebSocket(JSON.stringify(actions));
} catch (e) {
console.log('打开连接出错。');
console.log(e);
}
},
websocketOnErron: function() {
console.log('WebSocket连接出错了。');
try {
this.startAccetpMQMessage();
} catch (e) {
console.log('开始连接出错。');
console.log(e);
}
},
websocketOnClose: function() {
console.log('WebSocket连接断开了。');
try {
this.startAccetpMQMessage();
} catch (e) {
console.log('开始连接出错。');
console.log(e);
}
},
// 销毁webSocket的操作句柄
destroyWebSocket: function() {
try {
if (this.webSocketHandle != null) {
this.webSocketHandle.close();
this.webSocketHandle = null;
}
} catch (e) {
console.log('关闭连接出错。');
console.log(e);
}
}
}
};
</script>
<style>
</style>
项目中用到的webSocket(带安全验证)
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...