繁体   English   中英

Socket.IO将不响应

[英]Socket.IO will not respond

在服务器端,我无法将侦听器附加到客户端连接上以进行响应。 当客户端连接时,我可以成功发出一条消息,也可以从客户端成功响应服务器,但除此之外不能响应。

服务器

// communication scheme
//
// (1) server responds to client connection with 'welcome'
// (2) client immediately responds with 'thanks'
// (3) server's User class SHOULD respond with 'np', however this
//     is never emitted


class User {
    constructor(socket) {
        this.socket = socket;
        this.socket.on('thanks', function() {
            // !!! Point at which code doesn't work
            // the code inside here is never reached
            this.socket.emit('np');
        })
        this.socket.emit('welcome');
    }
}

class Server {
    constructor(port) {
        this.app = require('express')();
        this.server = require('http').Server(this.app);
        this.io = require('socket.io')(this.server);

        this.server.listen(port);
        this.io.on('connection', function(socket) {
            var user = new User(socket);
        });
    }
}

客户

this.io.on('welcome', function() {
    this.io.emit('thanks', {});
});

this.io.on('np', function() {
    console.log("I never get here either");
});

我认为它必须做到this一点的价值,而this要从'thanks'事件改变回调的主体。 this不再是指User对象,而是指称为函数user.socket的对象。 您基本上是在调用不存在的user.socket.socket.emit 有一个解决办法,将其范围存储在另一个变量中,以便我们以后可以访问它。

 class User { constructor(socket) { this.socket = socket; var that = this; this.socket.on('thanks', function() { // !!! Point at which code doesn't work // the code inside here is never reached that.socket.emit('np'); }) this.socket.emit('welcome'); } } 

您试图访问User.socket,但实际上是在尝试从服务器发出'np'时访问User.socket.socket。 我将其更改为使用ES6箭头功能来解决此问题,如果您想阅读一些箭头功能,这应该可以很好地解释它。

 class User { constructor(socket) { this.socket = socket; this.socket.on('thanks', () => { this.socket.emit('np'); }); this.socket.emit('welcome'); } } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM