[英]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.