简体   繁体   English

Socket.IO将不响应

[英]Socket.IO will not respond

On my server side, I can't get a listener attached to a client connection to respond. 在服务器端,我无法将侦听器附加到客户端连接上以进行响应。 I can successfully emit a message when a client connects, as well as successfully respond to the server from the client side, but can't respond beyond that. 当客户端连接时,我可以成功发出一条消息,也可以从客户端成功响应服务器,但除此之外不能响应。

Server 服务器

// 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);
        });
    }
}

Client 客户

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

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

I think it has to do the value of this which changes in the body of the callback from the 'thanks' event. 我认为它必须做到this一点的价值,而this要从'thanks'事件改变回调的主体。 this no longer refers to the User object, it refers to the object which called the function which is user.socket . this不再是指User对象,而是指称为函数user.socket的对象。 You are basically calling user.socket.socket.emit which doesn't exist. 您基本上是在调用不存在的user.socket.socket.emit There is a trick around this, store the scope of this in another variable so we can access it later. 有一个解决办法,将其范围存储在另一个变量中,以便我们以后可以访问它。

 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'); } } 

You were trying to access User.socket but were actually accessing the User.socket.socket when trying to emit 'np' from the server. 您试图访问User.socket,但实际上是在尝试从服务器发出'np'时访问User.socket.socket。 I changed it to use an ES6 arrow function to fix the issue, if you want to read up on it some arrow function this should explain it pretty well. 我将其更改为使用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