1.index.html代码示例
<div id="websocket" style="display:none;position: absolute;color:red;background-color: black;width: 100%;height: 100%;z-index: 100; opacity: 0.9; padding-top: 30%;padding-left: 30%; padding-border:1px; "onclick="closeDiv()"></div>
2.index.html的js代码示例
<script>// 创建一个WebSocket连接const socket = new WebSocket("ws://"+window.location.host+':48080/infra/ws?token='+window.localStorage.getItem('refreshToken'));var content = "";// 监听连接打开事件socket.addEventListener('open', (event) => {document.getElementById('websocket').style.display = 'none';console.log('WebSocket is open now.');});function closeDiv() {document.getElementById('websocket').style.display = 'none';}// 监听消息事件socket.addEventListener('message', (event) => {// this.content = JSON.parse(JSON.parse(event.data).content).text;this.content = JSON.parse(JSON.parse(event.data).content).content;document.getElementById('websocket').innerHTML = this.content;document.getElementById('websocket').style.display = 'block';console.log('Message from server: ', event.data);});// 监听错误事件socket.addEventListener('error', (error) => {console.error('WebSocket encountered error: ', error);});// 监听连接关闭事件socket.addEventListener('close', (event) => {console.log('WebSocket is closed now.');});
</script>
3.websocket需要token来连接,所以需要实时获取最新token
// 获取token
export const getAccessToken = () => {window.localStorage.setItem('refreshToken', wsCache.get(AccessTokenKey) ? wsCache.get(AccessTokenKey) : wsCache.get('ACCESS_TOKEN'))return wsCache.get(AccessTokenKey) ? wsCache.get(AccessTokenKey) : wsCache.get('ACCESS_TOKEN')
}// 刷新token
export const getRefreshToken = () => {window.localStorage.setItem('refreshToken', wsCache.get(RefreshTokenKey))return wsCache.get(RefreshTokenKey)
}