Websocket是一种用于H5浏览器的实时通讯协议,可以做到数据的实时推送,可适用于广泛的工作环境,例如客服系统、物联网数据传输系统,该测试工具可用于websocket开发初期的测试工作。
//订阅
subScribe() {
let _this = this;
var xhr = new XMLHttpRequest();
xhr.open('GET', "http://192.168.0.102:8033...");
xhr.send(null);
xhr.onreadystatechange = function () {
if (xhr.status === 200 && xhr.readyState === 4) {
_this.initWebSocket();
}
}
},
//初始化websocket
initWebSocket() {
if ('WebSocket' in window) {
const hsurl = "ws://192.168.0.102:8033...."
this.websocket = new WebSocket(hsurl);
this.websocket.onopen = this.websocketonopen;
this.websocket.onerror = this.websocketonerror;
this.websocket.onmessage = this.websocketonmessage;
this.websocket.onclose = this.websocketonclose;
} else {
return this.$message({
message: "当前浏览器不支持WebSocket",
type: "erroe",
duration: 1000
})
}
},
websocketonopen() {
console.log("WebSocket连接成功");
//发送请求,向websocket请求数据
},
websocketonerror(e) {
//错误
console.log("WebSocket连接发生错误");
},
websocketonmessage(e) {
let _this = this;
console.log(e);
//数据接收
//处理器handler
let receiveData = e.data;
console.log(receiveData);
if (receiveData != "连接成功") {
//该做什么
}
}
},
websocketonclose(e) {
//关闭
console.log("断开连接", e);
}