【问题标题】:Creating a hello world application with socket.io使用 socket.io 创建一个 hello world 应用程序
【发布时间】:2011-02-10 13:02:15
【问题描述】:

当我在客户端上运行时,会打印 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");
  }) 
}); 

【问题讨论】:

  • 在这种情况下您期望什么日志消息?简单连接只会在客户端输出“on connect”。如果您正在运行 Firefox,请确保 Firebug 正在运行,否则您将看不到日志。

标签: javascript node.js socket.io cygwin


【解决方案1】:

试试

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

而不是

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2017-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-07
      • 1970-01-01
      • 1970-01-01
      • 2016-04-25
      • 1970-01-01
      相关资源
      最近更新 更多