Socket.io emit callback not firing on server side? - node.js

My server emits events properly, but the emit callback never works. In the following, nothing is logged on my console:
Server:
io.sockets.emit('delete hint', {id: id}, function(data){
console.log('callback');
});
Client:
socket.on('delete hint', function(data){
// display a message before deleting
$('#' + data.id).fadeOut(function(){
$(this).remove();
});
});
I've also tried the client side code as function(data, fn) in case the callback needed to be included on the receiving function.
I'm using windows and my command prompt shows the following when socket.io is emitting the event:
websocket writing 5:::{"name":"delete hint", "args":[{"id":"1"}, null]}
I can't figure out what the problem is, what am I doing wrong?

A callback is executed on the sender computer when the receiver computer calls it
Have a look at this code:
Server:
io.sockets.on('connection', connectionFunc);
function connectionFunc (socket) {
socket.emit('delete hint', "data for client", callThis);
}
//this function is executed when client calls it
function callThis (dataFromClient){
console.log("Call back fired: " + dataFromClient);
}
Client:
socket.on('delete hint', function(data, callback) {
console.log("i received: "+ data);
// call back will fire only when u the next line runs
callback("the callThis function on server will run");
});
You can do this the opposite way.

You need to call the callback.
socket.on('delete hint', function(data, cb){
// display a message before deleting
$('#' + data.id).fadeOut(function(){
$(this).remove();
cb(null, 'done');
});
});

Related

nodejs socket.io - connected to server but emit doesn't do anything

I'm starting to work with Socket.io and my nodeJS API
I succeeded to get my user connected, and showed a message on my server.
But now, I'm trying to send data to my client -> then server -> then client again etc.
But when I use emit nothing appends... So this i my code :
SERVER SIDE
io.on('connection', function(socket){
console.log("user connected") // I see that
socket.emit('text', 'it works!'); //
socket.on('test1', function (data) {
console.log('received 1 : '); // Never showed
console.log(data); // Never showed
});
}
CLIENT SIDE
var socket = io.connect(myUrl); // good connection
socket.emit ('test1', {map: 4, coords: '0.0'}); // never showed on the server side
socket.on('text', function(text) {
alert(text); // never showed
socket.emit('test', { "test": "test2" });
});
Any ideas?
thanks !
Your Starter Code seems to be valid, you need to check two things :
if you successfully included the socket.min.js in the client side
if you re having any error printed in the console
On the client side, you have to wait until the connection succeeds before it is safe to send data to the server. Connecting to the server is not synchronous or instantaneous (thus it is not ready immediately). You are trying to send data before the connection is ready.
Put your first send of data inside a socket.on('connect', ...) handler.
var socket = io.connect(myUrl); // good connection
// send some data as soon as we are connected
socket.on('connect', function() {
socket.emit ('test1', {map: 4, coords: '0.0'});
});
socket.on('text', function(text) {
alert(text); // never showed
socket.emit('test', { "test": "test2" });
});
this worked for me
CLIENT SIDE
//sending custom data to server after successful connection
socket.on('connect', function(){
this.socket.emit('client-to-server', {map: 4, coords: '0.0'});
});
//listening the event fired by the socket server
socket.on('server-to-client', function(dataSendbyTheServer){
// do whatever you want
console.log(dataSendbyTheServer);
});
SERVER SIDE
io.on('connection', function(socket) {
// listening the event fired by the client
socket.on('client-to-server', function (data) {
console.log('received 1 : ');
// sending back to client
io.emit('server-to-client', data)
});
});

Node.js emit not working on specific socket.on

I'm trying to send news to my client. On connect, it works great, but for some reason on broadcast2 it wont get any response client sided, even know its the same piece of code, and even that broadcast2's console.log is working.
Q: How can i make sure broadcast2 emit will work?
This works:
socket.on('message', function (data) {
console.log('message gotten');
socket.emit('news', { message: 'xxxx' });
});
this wont work:
socket.on('broadcast2', function (data) {
console.log("broadcast revieced");
socket.emit('news', { message: 'xxxx' });
});
this is node.js response:
total code in node.js
socket.on('message', function (data) {
console.log('message gotten');
});
socket.on('another-message', function (data) {
socket.emit('not-news', { hello: 'world' });
});
socket.on('broadcast2', function (data) {
console.log("broadcast revieced");
socket.emit('news', { message: 'xxxx' });
});
and this on the client side:
var socket = io.connect('mysite:8080');
function sender() {
console.log('sending tester');
socket.emit('sendertester', 2);
}
socket.on('connect',function(){
});
socket.on('tester', function(msg){
console.log("callback");
});
socket.on('news', function(message) {
console.log("INCOMMING NEWS");
console.log(message);
});
UPDATE 1:
The broadcast2 socket, sent by PHP:
function broadcast($message,$broadcast = 'broadcast2') {
$client = new Client(new Version1X('myurlhidden:8080'));
$client->initialize();
$client->emit($broadcast, ['message' => $message]);
$client->close();
}
UPDATE 2:
**Question two: Cause my broadcast2 is sent before the client sided is loaded, and then the client connects to the node, could that be the cause?
But in the same time, im already preloading the class that holds the broadcast2 emitter.
Using codeigniter framework.**
UPDATE 3
I was trying to check my theory on update 2, by having two users logged in, while user one trying to perform the trigger. user two gets no output, so i suppose that theory is busted.
The server cannot send a message to any socket before it is connected. You have to wait until you have something listening to receive what you are sending.
I wouldn't call close after the emit either, as you may close the connection before the client has received the message, emit doesn't wait for the client to receive the data before returning its asynchronous.
Instead let the clients close the connections when they terminate.

why emit not working inside socket

I am trying to send an event to socket inside the socket for example
io.on('connection', function (socket) {
socket.emit("connected", {msg: 1});
socket.on('funcb', function (data) {
console.log('funca sent following data');
console.log(data);
});
socket.on('funca', function (data) {
console.log(data);
socket.emit('funcb', data);
});
});
funca is called from client/browser and it try to call the funcb but func b not working any ideas?
To explain what #bolav said with code:
Client side:
socket.emit("connected", {msg: 1});
socket.on('funcb', function (data) {
console.log('funcb from server sent following data');
console.log(data);
});
socket.on('funca', function (data) {
console.log(data);
socket.emit('funcb', data);
});
Server Side:
socket.on('funcb', function (data) {
console.log('funca from client side sent following data');
console.log(data);
socket.emit("funcb", data);
});
Might be the "emit" is just sending event back to client (browser) not socket itself, so it is unable to catch event 'funcb'
socket.emit('funcb', data) sent from the client will not invoke the socket.on('funcb') listener on the client. It will emit to the other side and invoke the socket.on listener on the server.

socket.io - callback on server emit() not executing

I just started using socket.io.js and am trying to get a function executed on the server as soon as I send a message to a client. My code is as follows,
server:
server.on('connection', onConnect);
var id = 0;
function onConnect(socket) {
socket.emit('myMsg', {id: ++id}, function () {console.log('id callback on server');});
}
client:
iosocket.on('myMsg', function(data, callback) {
console.log('id:', data.id, callback);
});
However I see that the callback function is displayed as 'undefined' on the client. From what I read on the docs I think this should work (https://github.com/LearnBoost/Socket.IO/wiki/Migrating-0.6-to-0.7+), so could someone please let me know what I am doing wrong here?
I think that the callback must be a function. Try this:
iosocket.on('myMsg', function(data, callback) {
console.log('id:', data.id);
callback();
});
See the acknowledgement section of the following link for an example:
http://socket.io/#how-to-use
if you would call callback as a function callback() on the client, it would activate your function on the server side, so it would console.log on your server.
if you just want to send a message from server to client, why make 2 callbacks? you can put it in data: {id:id,something:else).
if you want to log that something on the client;
if(data.something) {
console.log(data.something); //outputs "else"
}

Node.js/Express/Redis wait for only one message from channel

I have a redis connection subscribed to a channel with a get request
app.get('/wait', function (req, res) {
redisSub.on('message', function(channel, msg) {
console.log('rcv: ' + msg);
});
});
And later with a different get request I send the message
app.get('/done/:msg', function (req, res) {
redisPub.publish('message', req.params.msg);
});
The problem is that I want that request to stop listening for messages once it gets it. Or else when I go through again it will still be listening and will get the next message again. I'm not sure how to remove the listener from itself once the message is received.
Not tested but this should work,
var callback = function(channel, msg) {
console.log('rcv: ' + msg);
redisSub.removeListener('message', callback);
}
redisSub.on('message', callback);

Resources