feat: Establish Websocket communication.

This commit is contained in:
real-zony
2022-10-05 20:25:55 +08:00
parent 775e6140ee
commit f57afd4238
5 changed files with 89 additions and 12 deletions

View File

@@ -50,6 +50,9 @@
</template>
<script>
import Socket from "@/communication/socket";
import {mapMutations} from "vuex"
export default {
data: () => ({
drawer: null,
@@ -59,5 +62,19 @@ export default {
['mdi-information', '关于', '/about'],
],
}),
created() {
Socket.$on("message", this.handleGetMessage);
},
beforeDestroy() {
Socket.$off("message", this.handleGetMessage);
},
methods: {
...mapMutations({
setWsRes: "ws/setWsRes",
}),
handleGetMessage(msg) {
this.setWsRes(JSON.parse(msg));
}
}
}
</script>

View File

@@ -0,0 +1,29 @@
import Vue from 'vue'
// const wsUrl = process.env.VUE_APP_WS_URL;
const wsUrl = "ws://127.0.0.1:50001"
let socket = new WebSocket(wsUrl);
const emitter = new Vue({
methods: {
send(message) {
if (socket.readyState === 1) {
socket.send(JSON.stringify(message));
}
}, connect() {
socket = new WebSocket(wsUrl);
socket.onmessage = (msg) => {
this.$emit('message', msg.data);
};
socket.onerror = (err) => {
this.$emit('error', err);
};
socket.onclose = () => {
emitter.connect()
};
}
}
})
emitter.connect();
export default emitter;

View File

@@ -1,17 +1,13 @@
import Vue from 'vue'
import Vuex from 'vuex'
import ws from './ws'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
},
getters: {
},
mutations: {
},
actions: {
},
modules: {
}
state: {},
getters: {},
mutations: {},
actions: {},
modules: {ws}
})

21
src/ui/src/store/ws.js Normal file
View File

@@ -0,0 +1,21 @@
export const state = {
wsRes: {}
};
export const actions = {};
export const mutations = {
setWsRes(newState, payload) {
state.wsRes = payload;
}
};
export const getters = {};
export default {
state,
actions,
mutations,
getters,
namespaced: true
}

View File

@@ -28,6 +28,8 @@
</template>
<script>
import {mapState} from 'vuex'
import Socket from '@/communication/socket'
export default {
name: 'Home',
@@ -62,9 +64,21 @@ export default {
},
methods: {
openDir() {
Socket.send({
type: 'openDir',
data: {},
})
}
},
computed: {}
computed: {
...mapState({
wsRes: state => state.ws.wsRes
})
},
watch: {
wsRes(val) {
console.log('echo from server: ', val)
}
}
}
</script>