简单nodeJS示例不能与socket.io一起工作
一直在努力使这个简单的示例使用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页面时,没有脚本被嵌入,这是奇怪的..不知道是什么原因造成的。
你没有提供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);
您没有在您的index.html文件中正确加载socket.io库。试试这个:
<script type="text/javascript" src="http://localhost:8090/socket.io/socket.io.js"></script>
非常感谢,不知道我做错了什么! – thomaux 2011-12-19 07:53:58
+1,比从远程主机获取脚本更正确更好的方法。 – 2012-11-05 19:20:15
肯定,并注释以下行:
// server.listen(8090);
在客户端使用它作为路径!
<script type="text/javascript" src="/socket.io/socket.io.js"></script>
实际上有一些使用CDN版本的问题..对于我websockets没有工作..我建议坚持到本地版本 – noli 2011-05-02 15:01:30
啊,就是这样!我初始使用express,但回到http来隔离问题。我已经回去表达并开始使用app.configure('development')函数。谢谢你的帮助! – crawf 2011-05-03 01:09:46