websocket和SSE通信示例(无需安装任何插件)
data(){
return {
heartBeatInterval:5000,// 心跳间隔时间,单位为毫秒
webSocket:null,
heartBeatTimer:null,
}
},
mounted() {
// this.initWebSocket();//方案1,全双工通信websocket,部署线上后要使用wss,要求线上是域名且为https
this.createSseConnect();//方案2,sse,单工通信(http长连接)
},
methods:{
// sse建立连接
createSseConnect(){
let self = this;
if(window.EventSource){
const eventSource = new EventSource(`${this.$sseUrl}/sse/createConnect?clientId=${this.$store.state.user.name}`);
eventSource.onmessage = (e) =>{
console.log("msg info:", e.data);
self.handleMessage(JSON.parse(e.data))
};
eventSource.onopen = (e) =>{
console.log("已建立连接~")
};
eventSource.onerror = (e) =>{
if (e.readyState == EventSource.CLOSED) {
console.log("连接关闭");
} else if (eventSource.readyState == EventSource.CONNECTING) {
console.log("正在重连");
} else {
console.log('error', e);
}
};
eventSource.close = (e) =>{
console.log("连接关闭");
};
}else{
console.log("你的浏览器不支持消息通信~")
}
console.log(" 测试 打印")
},
handleMessage(data) {
this.msgContent = data.messageTitle;
this.messageId = data.messageId;
this.newMsgCount = data.newInfoCount;
if(this.msgContent){
this.showMessagePop = true;
}
},
initWebSocket() {
this.webSocket = new WebSocket(`${this.$websocketUrl}/websocket/${this.$store.state.user.name}`);
this.webSocket.onopen = () => {
// 建立连接后开始发送心跳包
this.startHeartBeat();
};
this.webSocket.onmessage = (event) => {
// 处理服务器发送的消息
this.handleMessage(JSON.parse(event.data))
};
this.webSocket.onclose = () => {
console.log('WebSocket连接已关闭');
// 连接关闭后停止心跳包
this.stopHeartBeat();
// 可根据需要重新连接
// reconnect();
};
},
startHeartBeat() {
// 每隔一段时间发送心跳包
this.heartBeatTimer = setInterval(() => {
if (this.webSocket.readyState === this.webSocket.OPEN) {
this.webSocket.send('hello,这是一个心跳包'); // 发送心跳包
}
}, this.heartBeatInterval);
},
stopHeartBeat() {
// 停止心跳包发送
clearInterval(this.heartBeatTimer);
},
}
target: 'ws://x.x.x.x:8080',
1.当确认请求地址无误,postman也可以请求通,但是唯独在项目中请求一直pending时,前端可以在devServer中配置compress:false,
参数来解决。
2.当本地请求正常,部署到线上之后就一直请求超时,statuscode栏显示已屏蔽mixed-content
,让后端在nginx配置中加上buffer相关的配置即可