开发者

Connect / node.js - creating a simple server

开发者 https://www.devze.com 2023-03-04 20:21 出处:网络
I\'m trying to get connect / node.js to work together nicely and simply. I have the following (in coffeescript)

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 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()

se开发者_运维百科rver.listen(8000)

socket = io.listen(server)

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

Which does work...


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号