qin*_*qin 5 sockets node.js socket.io vue.js vue-socket.io
我正在尝试在使用socket.io(localhost:8000)的express应用程序和使用vue-socket.io (localhost:8080)的vue应用程序之间创建socket.io通信。Express 应用程序正在接收来自 vue 应用程序的排放,但反之则不然。这是我的 Express 应用程序,但我很确定问题出在 vue 应用程序中:
后端快递
const port = 8000
const express = require("express")
const socket = require("socket.io")
const app = express()
const server = app.listen(port, () => {
console.log(`App is lisening to port ${port}...`)
} )
const io = socket(server)
io.on("connection", (socket) => {
console.log("connected to " + socket.id) //this is successfully getting logged
socket.on("chat", (msg) => {
console.log(socket.id + ": " + msg) //this is successfully getting logged when I click send
io.sockets.emit("chat", msg)
} )
} )
Run Code Online (Sandbox Code Playgroud)
我猜问题出在下面的某个地方:
前端 Vue(使用 CLI)
main.js:
import Vue from 'vue'
import App from './App.vue'
import VueSocketIO from 'vue-socket.io'
import SocketIO from 'socket.io-client'
Vue.use(new VueSocketIO( {
debug: true,
connection: SocketIO('http://localhost:8000')
} )
)
Vue.config.productionTip = false
new Vue({
render: h => h(App),
}).$mount('#app')
Run Code Online (Sandbox Code Playgroud)
聊天组件(Chat.vue)
<template lang="html">
<div>
<input type="text" v-model="input"/>
<button @click="send">Send</button>
</div>
</template>
<script>
export default {
sockets: {
//These dont work, nothing is printed to the console
connect: function () {
console.log('socket connected')
},
chat: function (msg) {
console.log("chat message recieved!: " + msg)
}
},
data(){
return {
input: ""
}
},
methods: {
send(){
this.$socket.emit('chat', this.input) //This works and is recieved by the express app!
}
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
我已经尝试解决这个问题一天了,但没有运气。
我的唯一目标再次是能够通过 Express 应用程序接收排放量。顺便说一句,如果有更好的方法在 vue 中使用 socket.io 而无需使用 vue-socket.io,我很乐意进行调查。
我只需使用vue-socket.io-extended而不是vue-socket.io就可以完成这项工作。就是这样,无需对代码进行重大更改。我知道从技术上讲这并不能解决使用 vue-socket.io 的问题,但在有人弄清楚这一点之前,我会将其作为未来搜索者的答案。
归档时间: |
|
查看次数: |
2432 次 |
最近记录: |