一直在努力使这个简单的例子使用socket.io努力工作.我最初在使用Cygwin的Windows 7上尝试过.此后也尝试过OS X,结果相同.
运行脚本时,它会显示...
2 May 20:57:47 - socket.io ready - accepting connections
Run Code Online (Sandbox Code Playgroud)
但访问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>
Run Code Online (Sandbox Code Playgroud)
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');
});
});
Run Code Online (Sandbox Code Playgroud)
关于我可能做错的任何想法?没有显示任何控制台消息.值得注意的是,当我使用Firebug查看index.html页面时,没有嵌入任何脚本,这很奇怪.不确定是什么原因造成的.
您没有在index.html文件中正确加载socket.io库.试试这个:
<script type="text/javascript" src="http://localhost:8090/socket.io/socket.io.js"></script>
Run Code Online (Sandbox Code Playgroud)
你没有提供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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12793 次 |
| 最近记录: |