2011-05-02 53 views
5

一直在努力使這個簡單的示例使用socket.io工作。我已經用Cygwin在Windows 7上開始嘗試。從此也嘗試過OS X,結果相同。簡單nodeJS示例不能與socket.io一起工作

運行腳本時,它顯示了這個...

2 May 20:57:47 - socket.io ready - accepting connections 

但訪問index.html頁面犯規顯示客戶甚至已經連接。

的index.html

<html> 
<head> 
<script type="text/javascript" src="socket.io.js"></script> 
<script type="text/javascript"> 
    var socket = new io.Socket('localhost',{'port':8090}); 

    socket.connect(); 

    socket.on('connect', function(){ 
     console.log('connected'); 
     socket.send('hi!'); 
    }); 

    socket.on('message', function(data){ 
     console.log('message recived: ' + data); 
    }); 

    socket.on('disconnect', function(){ 
     console.log('disconected'); 
    }); 
</script> 
</head> 
<body></body> 
</html> 

server.js

var http = require('http'), io = require('socket.io'), 

server = http.createServer(function(req, res){ 
    res.writeHead(200, {'Content-Type': 'text/html'}); 
    res.end('<h1>Hello world</h1>'); 
}); 
server.listen(8090); 

var socket = io.listen(server); 
socket.on('connection', function(client){ 
    console.log('client connected'); 

    client.on('message', function(){ 
     console.log('message arrive'); 
     client.send('some message'); 
    }); 

    client.on('disconnect', function(){ 
     console.log('connection closed'); 
    }); 
}); 

什麼我可以做錯了任何想法?沒有任何控制檯消息正在顯示。值得注意的是,當我使用Firebug來查看index.html頁面時,沒有腳本被嵌入,這是奇怪的..不知道是什麼原因造成的。

回答

8

你沒有提供socket.io.js(或flash文件)。

我會建議更換使用CDN:

<script src="http://cdn.socket.io/stable/socket.io.js"></script>

或選擇使用express服務於socket.io.js文件。

編輯:

犯錯其實仔細一看你還沒有煮好的index.html 再次表示可以工作,但對於簡單的例子:

var fs = require('fs'); 
var index = fs.readFileSync('index.html'); 
//note the readFileSync is done only in the first tic 
. 
. 
. 
res.writeHead(200, {'Content-Type': 'text/html'}); 
res.end(index); 
+0

實際上有一些使用CDN版本的問題..對於我websockets沒有工作..我建議堅持到本地版本 – noli 2011-05-02 15:01:30

+0

啊,就是這樣!我初始使用express,但回到http來隔離問題。我已經回去表達並開始使用app.configure('development')函數。謝謝你的幫助! – crawf 2011-05-03 01:09:46

9

您沒有在您的index.html文件中正確加載socket.io庫。試試這個:

<script type="text/javascript" src="http://localhost:8090/socket.io/socket.io.js"></script> 
+0

非常感謝,不知道我做錯了什麼! – thomaux 2011-12-19 07:53:58

+0

+1,比從遠程主機獲取腳本更正確更好的方法。 – 2012-11-05 19:20:15

0

肯定,並註釋以下行:

// server.listen(8090); 
1

在客戶端使用它作爲路徑!

<script type="text/javascript" src="/socket.io/socket.io.js"></script> 
相關問題