通过promises了解socket.io异步启动/停止

时间:2014-10-20 04:10:02

标签: node.js sockets asynchronous coffeescript promise

我正在为应用程序添加socket-io广播功能。我正在使用(bluebird)承诺,并使用mocha进行测试。我想能够开始&异步停止服务器(用于生产开始/停止和测试隔离),但我发现必要的回调/事件的文档是不稳定的。似乎有一些事件在socket.io的顶层是不可用的。

如果有人熟悉此设置,我将非常感谢他们对以下代码的评论。我正确地谈到这个吗?我错过了什么吗?特别是我想知道如何提供正确的错误回调 - 事件/回调文档还不太清楚。

服务器启动和停止:

Promise = require 'bluebird'
_ = require 'lodash'

activityServer = null

start = ()->
  http = require('http')
  express = require('express')()
  server = http.createServer(express)
  io = require('socket.io')(server)
  new Promise (resolve, reject)->
    server.on 'listening', ->
      activityServer = io.attach(server)
        .of(ACTIVITY_NAMESPACE)
      resolve()
    server.listen(PORT)

disconnectAll = ()->
  Promise.map _.values(activityServer.server.nsps), (nsp)->
    new Promise (resolve, reject)->
      disconnecting = {}
      for id of nsp.connected
        disconnecting[id] = true
      if _.size(disconnecting) == 0
        resolve()
      else
        for id, socket of nsp.connected
          socket.on( 'disconnect', ((id)->
            ->
              delete disconnecting[id]
              if _.size(disconnecting) == 0
                resolve()
            )(id))
          socket.disconnect(true)

测试设置:

describe 'push activities', ->
  before ->
    server.start()

  after ->
    server.stop()

  client = null
  beforeEach ->
    client = connectClient()

  afterEach ->
    new Promise( (resolve, reject)->
      client.on( 'disconnect', ->
        console.log( 'closed client' )
        resolve() )
      client.on( 'error', (err)->
        reject(err)
      )
      client.close()
    ).then( ->
      server.disconnectAll()
    )

0 个答案:

没有答案