Socket.IO不会回应

时间:2016-12-29 05:39:53

标签: javascript node.js socket.io

在我的服务器端,我无法连接到客户端连接的侦听器进行响应。我可以在客户端连接时成功发出消息,并从客户端成功响应服务器,但不能做出响应。

服务器

function updateSpinner(obj)
{
    var contentObj = document.getElementById("content");
    var value = parseInt(contentObj.value);

    if(isNaN(value)){
            contentObj.value=0;
            return;
        }
    else{
    if(obj.id == "down" && value >= 1) {
        value--;
    } else if(obj.id == "up"){
        if(value > 99){alert("Max Value Reached"); contentObj.value=100; return;}
        value++;
    }
   }
    contentObj.value = value;
}

客户端

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

2 个答案:

答案 0 :(得分:1)

我认为必须执行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');
    }
}

答案 1 :(得分:1)

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

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