Django+Vue实现WebSocket连接的示例代码(2)

<template> <div> <el-button type="primary" @click="runFunction" >执行</el-button> <el-button type="primary" @click="connectWebSock" >显示</el-button> <div> <span v-for="i in socketMessage" :key="i">{{i}}</span> </div> </div> </template> <script> import R from '@/plugins/axios'; import ws from '@/plugins/socket' export default { data() { return { webSocket: '', socketMessage: [], } }, methods: { // 打开连接的处理 openSocket(e) { if (e.isTrusted) { const h = this.$createElement; this.$notify({ title: '提示', message: h('i', { style: 'color: teal'}, '已建立Socket连接') }); } }, // 连接时的处理 listenSocket(e) { if (e.data){ this.socketMessage.push(this.x2Str(e.data)) } }, // 连接webSocket connectWebSock() { let wsuri = process.env.BACKEND_URL + '/ws/job/' + this.selectFunctions this.webSocket = ws(wsuri, { open: e => this.openSocket(e), message: e => this.listenSocket(e), close: e => this.closeSocket(e) }) }, // 转码 x2Str(str) { if (str) { let reg = new RegExp("(?<=^b').*(?='$)") let result = str.replace(/(?:\\x[\da-fA-F]{2})+/g, m => decodeURIComponent(m.replace(/\\x/g, '%')) ) return reg.exec(result)[0] } }, // 执行方法 runFunction() { R.myRequest('GET','api/start_job/' + this.selectFunctions, {}, {}).then((response) => { if (response.hasOwnProperty('response')){ this.$message({ type: 'error', message: '服务端返回错误,返回码:' + response.response.status }); }; if (response.data == 'ok') { this.$message({ type: 'success', message: '开始执行[' + this.selectFunctions + ']' }); } }); } } } </script>

至此,实现前后端 websocket 通讯。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/17345b17e98ed5a36f548f136b35b10f.html