2013-01-05 30 views
2

app.js開始時,我得到失蹤socket.io.js

$節點app.js 信息:socket.io開始

然而,運行的index.html它說,它缺少

GET http://localhost:3000/socket.io/socket.io.js 404 (Not Found) localhost:5 
Uncaught ReferenceError: io is not defined 

我用NPM安裝socket.io表達

app.js

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

var io = require('socket.io'); 

var app = express() 
    , server = require('http').createServer(app) 
    , io = io.listen(server); 

app.configure(function(){ 
    app.set('port', process.env.PORT || 3000); 
    app.use(express.bodyParser()); 
}); 

io.sockets.on('connection', function (socket) { 
    socket.emit('news', { hello: 'world' }); 
    socket.on('my other event', function (data) { 
    console.log(data); 
    }); 
}); 

的index.html

<script src="/socket.io/socket.io.js"></script> 
<script> 
    var socket = io.connect('http://localhost'); 
    socket.on('news', function (data) { 
     console.log(data); 
    socket.emit('my other event', { my: 'data' }); 
    }); 
    </script> 
+0

從哪裏得到了socket.io的客戶端腳本?你可能沒有正確的。 – SamT

+0

@SamT,客戶端腳本與socket-io軟件包捆綁在一起。 – mekwall

回答

3

您的代碼看起來有點亂了。通過將其更改爲:

var express = require('express') 
    , http = require('http') 
    , app = express() 
    , server = require('http').createServer(app) 
    , io = require('socket.io').listen(server) 
    ; 

app.configure(function(){ 
    app.use(express.bodyParser()); 
}); 

io.sockets.on('connection', function (socket) { 
    socket.emit('news', { hello: 'world' }); 
    socket.on('my other event', function (data) { 
    console.log(data); 
    }); 
}); 

server.listen(process.env.PORT || 3000); 
+0

工作!謝謝 – archytect

+1

除非我在這裏錯過了一些東西,否則你的代碼也有點搞砸了。 ; P在變量聲明中,在每行的末尾以及每行的開頭都有逗號。 – Lev