Socket.io, Node, Corodva, can not receive a message from another client that is not the sender

0

I've been doing this for hours and I do not understand why it's not working for me, besides I've already done systems like chats and I never had a problem, this time is the first time I use Cordova and socket but I can not explain why it happens this.

It turns out that I have 2 open clients, one sends a message and the other receives, this does not work for me, it only works for me if the one who issues the message also listens to receive it.

My code is:

Client issuer:

socket.emit("callDriver", data);

Recipient client:

socket.on("sendToDriver", function(data){

    console.log(data);

})

Server:

var io = require('socket.io')(server);

io.on('connection', function(socket){

    socket.on('callDriver', function(data){

        console.log(data);

        socket.emit('sendToDriver', data);

    })

})

So if the receiving client waits for the message, it never arrives, but if the same sender is told to listen to "sendToDriver" there the message arrives.

I appreciate your help!

    
asked by Jonathan Schell 27.05.2018 в 22:46
source

1 answer

0

well, I had posted on English stackoverflow, I continued googling and could not find a solution, I created 2 new projects using socket.io, I modified things, etc, etc until I found the solution.

It is strange because according to the official documentation of Socket.io from the server side you must use "socket.emit ()" to send the data to the client, this way I only sent the data only to the same client that I had sent them to the server only, so I tried to change this "socket.emit" to "io.emit" (variable previously created in "var io = require ('socket.io') (server)") and it worked!

In conclusion what I changed was:

// Cambié esto:
io.on('connection', function(socket){

    socket.on('callDriver', function(data){

        console.log(data);

        socket.emit('sendToDriver', data);

    })

})

// por esto:
io.on('connection', function(socket){

    socket.on('callDriver', function(data){

        console.log(data);

        io.emit('sendToDriver', data);

    })

})

Thank you very much to the community!

    
answered by 28.05.2018 в 05:41