我正在尝试在使用 socket.io (localhost:8000) 的 express 应用程序和使用vue-socket.io (localhost:8080) 的 vue 应用程序之间创建一个 socket.io 通信。express 应用程序正在接收来自 vue 应用程序的排放,但反之则不然。这是我的快速应用程序,尽管我很确定问题出在 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)
} )
} )
我猜问题出在下面的某个地方:
前端 Vue(使用 CLI)
主.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')
聊天组件(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>
我一直试图弄清楚这一天,但没有运气。
再一次,我唯一的目标是能够在 express 应用程序前接收排放。作为旁注,如果有更好的方法在 vue 中使用 socket.io 而不使用 vue-socket.io,我很乐意进行调查。