0

如何在不同的路由中监听事件?类似于我正在尝试做的事情。例如:

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

我想我一定是错过了什么或做错了什么。

有任何想法吗?

4

1 回答 1

0

编辑:套接字中的命名空间可用于连接到与/. https://socket.io/docs/rooms-and-namespaces/#custom-namespaces

例子:

io.of('/chat').on('connection', function(socket){
  console.log('someone connected');
});

将此代码移出聊天中间件。它应该只执行一次。只需将其放在功能之外,它应该可以工作。

io.on('connection', (socket) => {
   console.log('a user connected')
   socket.on('disconnect', () => {
      console.log('user disconnected')
   })
   socket.on('chat.message', (msg) => {
      console.log('message: ' + msg)
      io.emit('chat.message', msg)
   })
});

要使套接字文件在与默认路由不同的路由上服务,path请在创建 io 实例时使用 config。

例子:

const io = new socket(server, { path: '/chat', serveClient: false });

更多信息:https ://socket.io/docs/server-api/#new-server-httpserver-options

于 2017-08-18T10:13:33.563 回答