websocket和SSE通信示例(无需安装任何插件)
源码示例(两种方案任意切换)
data(){return {heartBeatInterval:5000,// 心跳间隔时间,单位为毫秒webSocket:null,heartBeatTimer:null,}
},
mounted() {// this.initWebSocket();//方案1,全双工通信websocket,部署线上后要使用wss,要求线上是域名且为httpsthis.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);},}
注意事项
使用websocket要注意
- websocket一段时间后会自动关闭链接,所以要定时发送心跳包请求检测心跳以保证链接持续有效
- 在vue项目中配置代理时要注意target地址是ws协议的
target: 'ws://x.x.x.x:8080',
- websocket打包部署线上必须走wss,这就要求线上域名为https请求
使用SSE要注意
1.当确认请求地址无误,postman也可以请求通,但是唯独在项目中请求一直pending时,前端可以在devServer中配置compress:false,
参数来解决。
2.当本地请求正常,部署到线上之后就一直请求超时,statuscode栏显示已屏蔽mixed-content
,让后端在nginx配置中加上buffer相关的配置即可