最近开始接触socket.io这个模块,出了点问题,老手帮忙看下,我找不出原因来: windowXP 32位 服务器端:
var http = require('http');
var io =require('socket.io'),
fs =require('fs');
server = http.createServer().listen(8888);
var socketserver = io.listen(server);
server.on('request',function(req,res){
fs.readFile(__dirname+'/client.html',function(err,data){
if(err){
res.writeHead(500,{});
res.end("cannot connect");
}
res.writeHead(200,{'content-type':'text/html'});
res.end(data);
});
});
socketserver.on('connection',function(socket){
socket.emit('news',{'name':'lily'});
console.log('client connected');
});
客户端(client.html):
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
$(document).ready(function(){
var socket = io.connect("http://localhost:8888");
socket.on('news',function(data){
$('#info').html(data.name);
});
});
//document.write('text2 here');
</script>
<body>
<label id="info"></label>
text1 here
</body>
</html>
然后我启动服务器,控制台显示【info socket.io started】 打开浏览器(火狐、google),键入http://127.0.0.1:8888,却显示不出来“lily”,而且服务器端 也没有“client connected”字符串显示。这是不是意味着没有建立socket连接,为什么呢?? f5刷新一遍,倒是建立了链接。难道每次都要刷新下才能建立连接?