main.js
var websocket_url='ws://127.0.0.1:8282';
window.websocket = new WebSocket(websocket_url);
Vue.prototype.socket = window.websocket;
window.onload = function(){
setInterval(()=>{
console.log(window.websocket)
Vue.prototype.socket = window.websocket;
window.websocket.send(JSON.stringify({type:'ping'}))
},10000)
}
app组件内websocket事件。
监听websocket连接、消息、断线重连事件。
延时1秒钟后进行!
断开连接是window.websocket.close()
setTimeout(()=>{
window.websocket = that.socket;
console.log(websocket)
websocket.onopen=function (event) {
console.log('连接成功!')
};
websocket.onmessage=function (event) {
var res = JSON.parse(event.data);
// 视自己聊天服务器的自定义事件而定</