Connect / node.js - creating a simple server
Asked Answered
C

1

6

I'm trying to get connect / node.js to work together nicely and simply. I have the following (in 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' })

But I keep getting the following error:

TypeError: Cannot call method 'listeners' of undefined

It seems the server is not being initialized in time for the socket to start listening.

Compare with:

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' })

Which does work?

Chelate answered 11/5, 2011 at 6:24 Comment(0)
O
5

Probably because .listen() returns something else. It should work if you rewrite your code like this:

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' })
Officinal answered 11/5, 2011 at 6:45 Comment(1)
Thank you! Working. So, I was setting server to the result of the listen method, rather than defining it, and calling listen on it.. Ah.Chelate

© 2022 - 2024 — McMap. All rights reserved.