Created
April 15, 2019 09:07
-
-
Save YanceyOfficial/109f8b73b88ea9c866ec750aeebfdfd2 to your computer and use it in GitHub Desktop.
[demo] sock.js + stomp.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template lang="pug"> | |
SomeComponent(:data="data") | |
</template> | |
<script lang="ts"> | |
import Vue from 'vue'; | |
import Component from 'vue-class-component'; | |
import { Watch } from 'vue-property-decorator'; | |
import SockJS from 'sockjs-client'; | |
import Stomp from 'stompjs'; | |
import SomeComponent from './SomeComponent.vue'; | |
@Component({ | |
components: { | |
SomeComponent, | |
}, | |
}) | |
export default class App extends Vue { | |
public data = []; | |
public stompClient: any = null; | |
public socket: any = null; | |
public mounted() { | |
this.initWebSocket(); | |
} | |
public destory() { | |
this.disconnect(); | |
} | |
// 连接成功后的初始化 | |
public successCallback() { | |
this.stompClient.subscribe(YOUR_RECEIVE_API, (payload: any) => { | |
this.data = JSON.parse(payload.body); | |
}); | |
this.sendMessage(YOUR_SEND_API, 5); | |
} | |
// 初始化连接 | |
public initWebSocket() { | |
this.socket = new SockJS(YOUR_WS_API); | |
this.stompClient = Stomp.over(this.socket); | |
this.stompClient.connect( | |
{ | |
Authorization: 'Basic XXXXXXXXXXXXXXXXXXXXX', | |
}, | |
(frame: any) => { | |
this.successCallback(); | |
}, | |
// 初始化失败时重新连接 | |
() => { | |
this.reconnect(YOUR_WS_API, this.successCallback); | |
}, | |
); | |
} | |
public reconnect(socketUrl: any, successCallback: any) { | |
let connected = false; | |
const reconInv = setInterval(() => { | |
this.socket = new SockJS(socketUrl); | |
this.stompClient = Stomp.over(this.socket); | |
this.stompClient.connect( | |
{}, | |
(frame: any) => { | |
// 连接成功,清除定时器 | |
clearInterval(reconInv); | |
connected = true; | |
successCallback(); | |
}, | |
() => { | |
console.log('重连接失败'); | |
if (connected) { | |
console.log('重连接成功'); | |
} | |
}, | |
); | |
}, 2000); | |
} | |
// websocket发送消息 body | |
public sendMessage(url: string, time: number) { | |
this.stompClient.send(url, {}, JSON.stringify({ minute: time })); | |
} | |
public disconnect() { | |
this.stompClient.disconnect(() => { | |
// todo | |
}); | |
} | |
} | |
</script> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment