0

当我在客户端上运行时,会打印 Hello World,但是我编写的控制台日志并未在客户端和服务器上都显示事件。为什么?

客户端代码:

<script src="C:\cygwin\usr\local\lib\node\.npm\socket.io\0.6.10\package\support\socket.io-client\socket.io.js"></script> 
<script> 
 var socket = new io.Socket('http://localhost:8080/'); 
 socket.connect();
 socket.on('connect', function(){
    console.log("on connect");

 }) ;
 socket.on('message', function(){ 
    console.log("on message");

 }) ;
 socket.on('disconnect', function(){ 
    console.log("on disconn");
 }) ;
</script> 

服务器代码:

var http = require('http'),  
    io = require('socket.io'), // for npm, otherwise use require('./path/to/socket.io') 

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

// socket.io 
var socket = io.listen(server); 
socket.on('connection', function(client){ 
  // new client is here! 
  client.on('message', function(){ 
    console.log("on message");
  }) 
  client.on('disconnect', function(){
    console.log("on disconnect");
  }) 
}); 
4

2 回答 2

1

尝试

var socket = new io.Socket('localhost:8080'); 

代替

var socket = new io.Socket('http://localhost:8080/');
于 2011-03-07T16:25:14.590 回答
0

这可能是因为浏览器同源安全限制 - socket.io 客户端库不是来自您连接的服务器。

我不知道相当古老的 0.6.9,但更新版本的socket.io自动服务 socket.io 客户端,所以你应该使用/socket/socket.io.js而不是file://你当前使用的 URL。检查文档以获取确切的 URL。

于 2011-09-05T19:26:28.213 回答