2013-01-25 63 views
1

我正在使用Express 3.0.6使用socket.io 0.9.13來製作一個Node應用程序。我甚至無法開始跑步,因爲它說socket.io沒有方法listen()。這裏是我的代碼(編譯CoffeeScript的,所以這是一個有點難看):Node.js:TypeError:Object socket.io沒有方法'偵聽'

(function() { 
    var app, express, io, port, usernames; 

    express = require('express'); 

    app = express(); 

    io = require('socket.io'.listen(3000)); 

    port = 3000; 

    app.listen(port); 

    console.log("Listening on port " + port); 

    console.log('CNTRL-C to quit.'); 

    app.engine('hamlc', require('haml-coffee'.__express)); 

    app.get('/', function(request, response) { 
    return response.render('index.hamlc'); 
    }); 

    usernames = {}; 

    io.sockets.on('connection', function(socket) { 
    socket.on('send-chat', function(msg) { 
     return io.sockets.emit('update-chat', socket.username, msg); 
    }); 
    socket.on('add-user', function(username) { 
     socket.username = username; 
     usernames[username] = username; 
     socket.emit('update-chat', 'SERVER', "You have connected as " + username + "."); 
     socket.broadcast.emit('update-users', 'SERVER', "" + username + " has joined the chat."); 
     return io.sockets.emit('update-users', usernames); 
    }); 
    return socket.on('disconnect', function() { 
     delete usernames[socket.username]; 
     io.sockets.emit('update-users', usernames); 
     return socket.broadcast.emit('update-chat', 'SERVER', "" + socket.username + " has disconnected from chat"); 
    }); 
    }); 

}).call(this); 

這就提出了以下錯誤:

node.js:201 
     throw e; // process.nextTick error, or 'error' event on first tick 
      ^
TypeError: Object socket.io has no method 'listen' 
    at Object.<anonymous> (/Users/chris/src/web/kouv/app.js:8:28) 
    at Object.<anonymous> (/Users/chris/src/web/kouv/app.js:44:4) 
    at Module._compile (module.js:432:26) 
    at Object..js (module.js:450:10) 
    at Module.load (module.js:351:31) 
    at Function._load (module.js:310:12) 
    at Array.0 (module.js:470:10) 
    at EventEmitter._tickCallback (node.js:192:40) 

回答不勝感激。 :-)

回答

4

試試這個:

var express = require('express'), 
    http = require('http'); 

var app = express(); 
var server = http.createServer(app); 

var io = require('socket.io').listen(server); 
server.listen(3000); 

Socket.io基本劫持HTTP對象在運行時; express 3.xx不再運行在http.server上,所以有必要爲socket.io創建自己的實例來使用它。

+0

就像你說的那樣,但它仍然顯示相同的錯誤。 – beakr

+0

啊......我明白了。 'require'socket.io'.listen(server)'編譯爲'require('socket.io'.listen(server))' – beakr

+0

@beakr我猜@ari意思是'express = require('express');而不是'http = require('http');' –

相關問題