65 lines
1.5 KiB
JavaScript
65 lines
1.5 KiB
JavaScript
export const namespaced = true
|
|
|
|
export const state = () => ({
|
|
socket: null,
|
|
isConnected: false,
|
|
messages: [],
|
|
notices: [],
|
|
count: "0"
|
|
})
|
|
|
|
export const mutations = {
|
|
WEBSOCKET_INIT(state,url){
|
|
state.socket = new WebSocket(url);
|
|
state.socket.onopen=function () {
|
|
console.log("WebSocket连接成功");
|
|
};
|
|
state.socket.onmessage = function (e) {
|
|
console.log(e,'接收到的消息')
|
|
if (e.data.startsWith("C")) {
|
|
state.count = e.data;
|
|
}
|
|
else if (e.data.startsWith("系统通知")){
|
|
state.notices.push(e.data);
|
|
}else if (e.data.startsWith("close")){
|
|
console.log(e.data)
|
|
} else {
|
|
state.messages.push(JSON.parse(e.data));
|
|
console.log(state.messages);
|
|
}
|
|
};
|
|
state.socket.onerror= function () {
|
|
console.log("WebSocket连接发生错误");
|
|
};
|
|
state.socket.onclose = function (e) {
|
|
console.log("connection closed (" + e.code + ")");
|
|
};
|
|
},
|
|
WEBSOCKET_SEND(state,msg){
|
|
state.socket.send(msg);
|
|
},
|
|
WEBSOCKET_CLOSE(state){
|
|
if (state.socket) {
|
|
state.socket.close();
|
|
state.socket = null;
|
|
}
|
|
},
|
|
SET_MESSAGE(state,msg){
|
|
state.messages = msg
|
|
}
|
|
}
|
|
|
|
export const actions = {
|
|
websocket_init({commit}, url) {
|
|
commit('WEBSOCKET_INIT', url)
|
|
},
|
|
websocket_send({commit}, msg) {
|
|
commit('WEBSOCKET_SEND', msg)
|
|
},
|
|
websocket_close({commit}){
|
|
commit('WEBSOCKET_CLOSE')
|
|
},
|
|
set_message({commit},msg){
|
|
commit('SET_MESSAGE',msg)
|
|
}
|
|
} |