简体   繁体   中英

socket.io emit callback not firing

function MainController () {
 var self = this;

self.mainInfo = null;

self.socket = io.connect('http:/192.168.56.101:3000');

self.login = function () {
self.socket.emit("login", "Hello");
}


self.socket.on('welcome', function () {
console.log('welcome');
});

self.socket.on('player leave', function () {
console.log('leave');
});


self.login();
};

Above is front-end code. I can receive emit messages, google chrome logs incoming message

5:::{"name":"welcome"}

But console.log('welcome'); doesn't work. callback's don't fire

错别字:(

 self.socket = io.connect('http://192.168.56.101:3000');

You need to put self.login() inside 'connect' event handler because at the time login() got called, it's not guaranteed that the connection is established.

self.socket = io.connect('http://192.168.56.101:3000');

    :
    :

self.socket.on('connect', function() {
    self.login();
}

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