如何在不同的路由中监听事件?这类似于我正在尝试做的事情。例如:
import Koa from 'koa'
import serve from 'koa-static'
import Router from'koa-router'
import views from 'koa-views'
import socket from 'socket.io'
import http from 'http'
import config from'./config'
const app = new Koa()
const router = new Router()
const server = http.createServer(app.callback())
const io = new socket(server)
app.use(async function (ctx, next) {
ctx.io = io
await next()
})
const test1 = async(ctx, next) => {
ctx.io.on('connection', (socket) => {
console.log('a user connected - event 1')
socket.on('disconnect', () => {
console.log('user disconnected')
})
socket.on('Event1', (data) => {
console.log('Event1')
})
})
await ctx.render('test1', {});
}
const test2 = async(ctx, next) => {
ctx.io.on('connection', (socket) => {
console.log('a user connected - event 2')
socket.on('disconnect', () => {
console.log('user disconnected')
})
socket.on('Event2', (data) => {
console.log('Event2')
})
})
await ctx.render('test2', {});
}
router
.get('/', function (ctx, next) {
ctx.body = 'Hello World!';
})
.get('/test1', test1)
.get('/test2', test2)
app.use(serve(config.static_dir.root))
app.use(views(__dirname + config.template.path, config.template.options))
app
.use(router.routes())
.use(router.allowedMethods())
server.listen(config.server.port)
它们工作正常但有问题 - 当您刷新浏览器 3 次时'/test1'
,io 实例将被重复,所以我将在下面得到重复的结果:
a user connected - event 1
a user connected - event 1
a user connected - event 1
我想我一定是错过了什么或做错了什么。
有任何想法吗?