简体   繁体   中英

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 no longer refers to the User object, it refers to the object which called the function which is user.socket . You are basically calling user.socket.socket.emit which doesn't exist. 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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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