简单的nodeJS示例不适用于socket.io
一直在努力使这个简单的例子使用socket.io工作。 我已经用Cygwin在Windows 7上开始尝试。 从此也尝试过OS X,结果相同。
当运行脚本,它显示这个…
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页面,没有脚本被embedded,这是奇怪的..不知道是什么原因造成的。
你没有提供socket.io.js(或Flash文件)。
我build议使用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);
你没有正确加载你的index.html文件中的socket.io库。 尝试这个:
<script type="text/javascript" src="http://localhost:8090/socket.io/socket.io.js"></script>
在客户端使用这个作为path!
<script type="text/javascript" src="/socket.io/socket.io.js"></script>
是的,并注释以下行:
// server.listen(8090);