【发布时间】:2021-03-17 10:15:32
【问题描述】:
我尝试创建一个小应用程序并想向其中添加 websockets,但我在连接时遇到了一些问题。我正在使用 nuxt-socket-io 和 socket io。
const socket = require('socket.io')
// Options can be host, port, ioSvc, nspDir:
module.exports = (app) => {
let server = null
let io = null
app.use('/ws', (req, res) => {
if (!server) {
server = res.connection.server
io = socket(server)
io.on('connection', function (socket) {
console.log('Made socket connection')
socket.on('msg', (msg) => {
console.log('Recived: ' + msg)
setTimeout(() => {
socket.emit('msg', `Response to: ${msg}`)
}, 1000)
})
socket.on('disconnect', () => console.log('disconnected'))
})
}
res.json({ msg: 'server is set' })
})
}
这是用于在服务器上创建套接字
我的 nuxt-config 是
['nuxt-socket-io', {
sockets: [ // Required
{ // At least one entry is required
name: 'main',
url: 'http://localhost:3000/api/ws',
path: 'ws',
default: true
}
],
server: false
}],
然后在我的 .vue 文件中
mounted () {
this.socket = this.$nuxtSocket({
path: '/api/ws'
})
},
methods: {
callSocket () {
console.log('trying to call socket')
this.socket.emit('msg', 'test message', (resp) => {
console.log(resp)
this.resp = resp
})
}
}
我收到服务器的响应
{"msg":"server is set"}
但我从来没有连接过
console.log('Made socket connection')
但我似乎无法连接以运行任何发射,我不知道为什么
你可以在https://github.com/Chris9540/mappertron看到完整的代码仓库 如果这有助于让您对正在发生的事情有更多的了解 这是我第一次尝试添加套接字,所以我可能会完全错误地做这件事
【问题讨论】:
标签: node.js express sockets nuxt.js