<template>
<div class="ws">
<!-- <input id="name" value="" placeholder="用户名"> -->
<!-- <button id="login" type="button" @click="login(wsUrl)" value="">登陆</button> -->
<!-- <br/><br/> -->
<p>{{onTxt}}</p>
<input id="data" v-model="message" placeholder="请输入消息">
<button type="button" @click='wsSend();'>发送消息</button>
<p class="holdTxt">{{message}}</p>
<!-- <br/><br/> -->
<div id="info">
</div>
</div>
</template>
<script>
export default {
data(){
return {
// 测试 ws 在线地址
// wsUrl: 'ws://121.40.165.18:8800', // http://www.websocket-test.com/
// wsUrl: 'ws://123.207.136.134:9010/ajaxchattest', // http://coolaf.com/tool/chattest
// wsUrl: 'ws://echo.websocket.org', // 参考 http://www.bejson.com/httputil/websocket/
wsUrl: 'wss://echo.websocket.org', // 参考 https://www.toolfk.com/tool-online-runwebsocket
// WebSocket 相关 start
message: '',
onTxt: '',
lockReconnect: false,
ws: null,
//心跳检测
heartCheck: {
timeout: 10000, //发一次心跳时间
timeoutObj: null,
serverTimeoutObj: null,
reset: function(){
clearTimeout(this.timeoutObj);
clearTimeout(this.serverTimeoutObj);
return this;
},
start: function(enWs){
var that = this;
this.timeoutObj = setTimeout(function(){
//这里发送一个心跳,后端收到后,返回一个心跳消息,
//onmessage拿到返回的心跳就说明连接正常
enWs.send("ping");
console.log("ping! —— 发出心跳");
that.serverTimeoutObj = setTimeout(function(){//如果超过一定时间还没重置,说明后端主动断开了
enWs.close(); //如果onclose会执行reconnect,我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
console.log("后端断开了");
}, that.timeout)
}, this.timeout)
}
}
// WebSocket 相关 end
}
},
filters: {
},
methods: {
// 格式化时间 返回: "2019/01/01 01:02:03" 时间格式
// 传入时间戳:格式化 / 不传参:返回当前时间
formatTime(timestamp) {
let nowDate;
timestamp ? nowDate = new Date(timestamp) : nowDate = new Date()
let Y = nowDate.getFullYear() + '/';
let M = (nowDate.getMonth() + 1 < 10 ? '0' + (nowDate.getMonth() + 1) : nowDate.getMonth() + 1) + '/';
let D = nowDate.getDate() + ' ';
let h = nowDate.getHours() + ':';
let m = nowDate.getMinutes() + ':';
let s = nowDate.getSeconds();
return Y + M + D + h + m + s;
},
// login(url) {
// let that = this;
// console.log('login--url: ', url)
// if (!that.ws) {
// console.log('if');
// var user = document.getElementById("name").value;
// try {
// console.log('try');
// that.ws = new WebSocket('ws://123.207.167.163:9010/ajaxchattest');
// console.log('that.ws', that.ws);
// that.ws.onopen = function (event) {
// console.log("onopen 已经与服务器建立了连接...", event);
// console.log("登陆成功,可以开始聊天了")
// };
// that.ws.onmessage = function (event) {
// console.log("onmessage 接收到服务器发送的数据...", event);
// // let data = event.data.split(' [');
// // console.log('data', data);
// document.getElementById("info").innerHTML += event.data + "<br>";
// };
// that.ws.onclose = function (event) {
// console.log("onclose 已经与服务器断开连接...", event);
// };
// that.ws.onerror = function (event) {
// console.log("onerror WebSocket异常!", event);
// };
// } catch (ex) {
// console.log('try', ex.message);
// }
// document.getElementById("login").innerHTML = "退出";
// } else {
// console.log('else')
// that.ws.close();
// that.ws = null;
// }
// },
// SendData() {
// var data = document.getElementById("data").value;
// try {
// this.ws.send(data);
// } catch (ex) {
// console.log(ex.message);
// }
// },
initWs(url) {
let that = this;
console.log("initWs_wsUrl:", url);
try{
console.log("initWs_try");
if(typeof WebSocket != 'undefined'){
console.log("您的浏览器支持websocket协议!");
that.ws = new WebSocket(url);
// that.initEventHandle();
console.log('readyState', that.ws.readyState);
that.ws.onclose = function (e) {
console.log("WS_onclose: ", e);
console.log('WS_onclose--readyState', that.ws.readyState);
that.reconnect(that.wsUrl);
console.log("连接关闭!", that.formatTime());
that.onTxt = '连接--no--关闭!'
};
that.ws.onerror = function (e) {
console.log("WS_onerror: ", e);
console.log('WS_onerror--readyState', that.ws.readyState);
that.reconnect(that.wsUrl);
console.log("连接错误!", that.formatTime());
that.onTxt = '连接--error--错误!'
};
that.ws.onopen = function (e) {
console.log("WS_onopen: ", e);
console.log('WS_onopen--readyState', that.ws.readyState);
that.heartCheck.reset().start(that.ws); //心跳检测重置
console.log("连接成功!", that.formatTime());
that.onTxt = '连接--ok--成功!'
};
that.ws.onmessage = function (res) { //如果获取到消息,心跳检测重置
that.heartCheck.reset().start(that.ws); //拿到任何消息都说明当前连接是正常的
console.log('WS_onmessage--readyState', that.ws.readyState);
// console.log("收到消息!", that.formatTime(), res);
let reg = /^ping/;
if(!reg.test(res.data)){ // 非心跳消息
console.log("消息如下: ");
console.log(res);
that.msgHandle(res);
}
// else{
// console.log("res.data", res.data)
// }
};
}
// else if('MozWebSocket' in window){
// console.log("您的浏览器支持websocket协议!");
// that.ws = new MozWebSocket(url);
// }
else{
console.log("您的浏览器--不--支持websocket协议!");
}
} catch (e){
that.reconnect(that.wsUrl);
console.log('initWs_catch: ', e);
}
},
// initEventHandle() {
// let that = this;
// that.ws.onclose = function (e) {
// console.log("onclose: ", e);
// that.reconnect(wsUrl);
// console.log("连接关闭!", that.formatTime());
// };
// that.ws.onerror = function (e) {
// console.log("onerror: ", e);
// that.reconnect(wsUrl);
// console.log("连接错误!", that.formatTime());
// };
// that.ws.onopen = function (e) {
// console.log("onopen: ", e);
// that.heartCheck.reset().start(); //心跳检测重置
// console.log("连接成功!", that.formatTime());
// };
// that.ws.onmessage = function (res) { //如果获取到消息,心跳检测重置
// that.heartCheck.reset().start(); //拿到任何消息都说明当前连接是正常的
// console.log("收到消息!", that.formatTime());
// if(res.data != 'pong'){ // 非心跳消息
// console.log("非心跳消息如下: ", res);
// }
// };
// },
reconnect(url) {
console.log("进入重连方法");
if(this.lockReconnect) return;
this.lockReconnect = true;
setTimeout(()=> { //没连接上会一直重连,设置延迟避免请求过多
this.initWs(url);
this.lockReconnect = false;
}, 2000);
},
wsSend(){
let data = this.message;
console.log("send data: ", data);
if(this.ws.readyState===1){
console.log("OK--当前状态", this.ws.readyState);
this.ws.send(data);
}else{
console.log("NO--当前状态", this.ws.readyState);
}
this.message = ''
},
msgHandle(res){
console.log("msgHandle —— data 消息:", res.data);
document.getElementById("info").innerHTML += res.data + "<br>";
},
closeWs(){
this.ws.close();
this.heartCheck.reset();
console.log("退出页面——关闭ws");
},
},
mounted(){
console.log("hello ws");
this.initWs(this.wsUrl);
},
beforeDestroy() {
},
destroyed() {
if(this.ws){
this.closeWs();
}
},
}
</script>
<style type="text/css" scoped>
.ws{
padding-top: 1.5rem;
}
#info{
width: 80%;
min-height: 1rem;
line-height: .4rem;
margin: 0 auto;
padding: .15rem;
text-align: left;
border: 1px solid #ccc;
}
.holdTxt{
height: .4rem;
margin-bottom: .1rem;
padding: 0 .5rem;
text-align: left;
background: #eee;
}
</style>
【学习随记】ws
最新推荐文章于 2023-08-21 17:21:25 发布