【问题标题】:Nodejs simple socket.io example not workingNodejs简单的socket.io示例不起作用
【发布时间】:2012-12-13 14:34:16
【问题描述】:

我有以下服务器端代码:

        var express = require('express')
          , http    = require('http')
          , routes  = require('./routes')
          , io      = require('socket.io')
          , factory = require('./serverfactory.js');
          var  app  = express();

          var server = app.listen(3000);
          io = io.listen(server);

          io.sockets.on('connection',function(socket){

            console.log('new user');

            socket.emit('hail','mysimplemsg');
            socket.on('customevent',function(msg){
                console.log(msg);       
            });
          });



        //var app = module.exports = express.createServer();

        // Configuration

        app.configure(function(){
          app.set('views', __dirname + '/views');
          app.set('view engine', 'jade');
          app.use(express.bodyParser());
          app.use(express.methodOverride());
          app.use(app.router);
          app.use(express.static(__dirname + '/public'));
        });

        app.configure('development', function(){
          app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
        });

        app.configure('production', function(){
          app.use(express.errorHandler());
        });

        // Routes
        app.get('/', routes.index);

这是客户端:

    var socket = io.connect('http://localhost:3000');
    socket.emit('customevent','work');
    socket.on('hail',function(msg){
        console.log(msg);
    });

我期待我的git console 输出new user(它确实如此)然后它应该输出work(它没有)然后我在我的浏览器控制台中得到一个消息mysimplemsg(它没有)。

为什么没有调用服务器端customevent 的事件以及为什么没有调用客户端hail 的事件?

【问题讨论】:

标签: node.js socket.io


【解决方案1】:

我认为问题在于您在连接之前从客户端发出 customevent。尝试添加一个连接处理程序并将您的客户端发射移动到其中:

var socket = io.connect('http://localhost:3000');    
socket.on('hail',function(msg){
    console.log(msg);
});
socket.on('connect',function(){
                      console.log('connected to socket.io server');
                      socket.emit('customevent','work');
                    });

如果连接处理程序没有命中,则验证您是否正确引用了客户端socket.io javascript库(jade语法):

script(type='text/javascript',src='/socket.io/socket.io.js')

【讨论】:

  • 感谢您的回复,我按照您所说的做了,但我仍然只能在日志中看到 new user 消息,我的 git 的日志中没有显示 work 消息。
  • socket.on('connect') 不工作。我调试代码,客户端没有在日志中发送任何内容。可能是什么问题?
  • 这段代码对我有用。验证您是否正确托管了 socket.io 客户端库。
  • 是的,我的托管是正确的。我不明白为什么这个事件没有被解雇,这让我发疯。我从 3 天开始就遇到了这个问题。
  • 我从socket.io/#how-to-use复制粘贴了完全相同的代码,但仍然是同样的问题。
【解决方案2】:

终于明白了。

它在 opera 上运行良好,但在 chrome and firefox 上却不行。我找到了this 链接,该人说要在服务器端插入此代码 sn-p。

io.configure('development', function(){
  io.set('transports', ['xhr-polling']);
});

现在一切正常。

【讨论】:

  • 对不起,我忘了在问题中提到浏览器问题。
  • 嗯,我想将 socket.io 用于 websocket,而不是用于 xhr-polling。不是解决方案。
猜你喜欢
  • 1970-01-01
  • 2011-09-18
  • 1970-01-01
  • 1970-01-01
  • 2012-07-01
  • 2015-11-23
  • 2016-03-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多