【问题标题】:Socket.io client cannot emit messageSocket.io 客户端无法发出消息
【发布时间】:2014-01-20 16:44:37
【问题描述】:

服务器:

var 
io=require('socket.io'),
express=require('express'),
UUID=require('node-uuid'),
path=require('path'),
app = express();

app.configure(function(){
    app.use(express.static(path.join(__dirname,'')));
});

var server = require('http').createServer(app).listen(8080);
sio = io.listen(server);

app.get('/', function(req, res){
    res.sendfile('/index.html', {root:__dirname});
});

sio.sockets.on('connection', function(socket){
    socket.userid = UUID();
    socket.on('message', function(){
        console.log('client just sent something');
        socket.emit('news', { hello: 'world' });
    });
});

客户端首先连接index.html,然后点击一个href到gameroom.html。这是gameroom.html:

<html>
<head>
    <script src="/socket.io/socket.io.js"></script>
    <script type="text/javascript" src="game.room.js"></script>
    <script type="text/javascript" src="client.js"></script>
</head>
</html>

client.js:

window.onload = function(){
    var game = new game_room();
}

game.room.js:

var game_room = function(){
    this.socket = io.connect();

this.socket.on('connect', function(){
    this.socket.emit('message', 'Hello server');
});
}

当客户端连接时,它应该发出消息并且服务器写入日志,但我没有得到任何日志。我在game.room.js中尝试了没有this.socket.on('connect')的代码,客户端可以发出消息,我得到了日志。另外,如果我将代码从 game.room.js 传输到 client.js,即在 window.onload 中,我创建了 var socket = io.connect() 和 socket.on('connect', function() {socket.emit( '消息', '你好服务器')});它工作正常。

有人可以帮助我或解释发生了什么吗?谢谢。

【问题讨论】:

    标签: node.js express socket.io


    【解决方案1】:

    你输了context你可以试试bind

    var game_room = function(){
        this.socket = io.connect();
    
    
        this.socket.on('connect', function(){
            this.socket.emit('message', 'Hello server');
        }.bind(this));
    }
    

    或者您可以将this.socket 设置为某个本地变量:

    var game_room = function(){
        var socket = this.socket = io.connect();
    
    
        this.socket.on('connect', function(){
            socket.emit('message', 'Hello server');
        });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-16
      • 1970-01-01
      • 1970-01-01
      • 2019-01-02
      • 1970-01-01
      • 1970-01-01
      • 2018-06-26
      相关资源
      最近更新 更多