Connect / node.js - 创建一个简单的服务器

时间:2011-05-11 06:24:02

标签: node.js connect coffeescript socket.io

我正在尝试让connect / node.js很好地协同工作。 我有以下(在coffeescript中)

connect = require('connect')
io = require('socket.io')

server = connect.createServer(
    connect.favicon()
  , connect.logger()
  , connect.static(__dirname + '/public')
).listen(8000)

socket = io.listen(server)
socket.on 'connection', (socket) ->
  socket.send({ hello: 'world' })

但是不断收到以下错误:

TypeError: Cannot call method 'listeners' of undefined

似乎服务器没有及时初始化套接字开始监听..

与:比较:

io = require ("socket.io")
http = require('http')

server = http.createServer()

server.listen(8000)

socket = io.listen(server)

socket.on 'connection', (socket) ->
  socket.send({ hello: 'world' })

哪个有用......

1 个答案:

答案 0 :(得分:5)

可能是因为.listen()会返回其他内容。如果你重写这样的代码它应该工作:

connect = require('connect')
io = require('socket.io')

server = connect.createServer(
    connect.favicon()
  , connect.logger()
  , connect.static(__dirname + '/public')
)
server.listen(8000)

socket = io.listen(server)
socket.on 'connection', (socket) ->
  socket.send({ hello: 'world' })