SSE单向通讯(serve-client)
参考连接:https://www.iteye.com/blog/jamie-wang-1849193,https://blog.csdn.net/qq_35067322/article/details/100022160?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-11.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-11.nonecase
created() {
if ("EventSource" in window) {
const that = this
var source = new EventSource(requestObj.default.BASE_URL + "pushHazard", {
withCredentials: true
});
source.onmessage = function(e) {
console.log(e)
};
source.onopen = function(e) {};
source.onerror = function(e) {
if (e.readyState == EventSource.CLOSED) {
} else {
// console.log("onerror:" + e.readyState);
}
};
// source.close();
} else {
console.log("没有sse");
};
},
webScoket双向通讯(参考:https://zhengkai.blog.csdn.net/article/details/91552993,https://zhengkai.blog.csdn.net/article/details/91552993)
data(){
return {
path: 'ws://192.168.3.70:6002',
socket: '',
}
},
methods: {
initWeb() {
if (typeof WebSocket === 'undefined') {
alert('您的浏览器不支持socket')
} else {
// 实例化socket
this.socket = new WebSocket(this.path) //path实在data中定义的地址
console.log(this.socket)
// 监听socket连接
this.socket.onopen = this.open
// 监听socket错误信息
this.socket.onerror = this.error
// 监听socket消息
this.socket.onmessage = this.getMessage
}
},
open: function () {
console.log('socket连接成功')
},
error: function () {
console.log('连接错误')
},
getMessage: function (msg) {
console.log(msg.data)
},
send: function () {
this.socket.send(params)
},
close: function () {
console.log('socket已经关闭')
},
}
遇到的问题:之前后台接口使用的是6000端口,在谷歌浏览器上连接失败,报"SecurityError: Failed to construct 'WebSocket': The port 6000 is not allowed."
原因:谷歌浏览器对某些端口做了限制https://blog.csdn.net/demolw/article/details/82020459,改到其它不受限制端口即可