Socket.IO不会回应
在我的服务器端,我不能让一个监听器连接到客户端连接来响应。 当客户端连接时,我可以成功地发出一条消息,并成功地响应客户端的服务器,但是除此之外无法做出响应。
服务器
// 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"); });
我认为它必须在“感谢”事件的callback的主体中做this
变化的价值。 this
不再引用User对象,它指的是调用了user.socket
这个函数的对象。 你基本上调用了不存在的user.socket.socket.emit
。 这里有一个技巧,将其范围存储在另一个variables中,以便稍后访问它。
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,但实际上访问User.socket.socket当试图从服务器发出'np'
。 我改变它使用ES6箭头函数来解决这个问题,如果你想读一些箭头函数,这应该解释得很好。
class User { constructor(socket) { this.socket = socket; this.socket.on('thanks', () => { this.socket.emit('np'); }); this.socket.emit('welcome'); } }