Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to be sure that message via socket.io has been received to the client?

Tags:

How to check that message sent with socket.io library has been received to the client. Is there special method for it in socket.io?

Thanks for your answers!

like image 534
Bart Avatar asked Jul 08 '12 10:07

Bart


People also ask

How do I check if a message sent through socket.io is read?

You will have to send a message back when the message is read. There is no notion of when something is "read" in socket.io. That's something you would have to invent in your own user interface and when you consider it read, you could send a message back to the sender that indicates it is now read.

How do I know if socket.io client is connected?

You can check the socket. connected property: var socket = io. connect(); console.

How do I connect socket.io to client side?

var socket = require('socket. io-client')('ws://ws.website.com/socket.io/?EIO=3&transport=websocket'); socket. on('connect', function() { console. log("Successfully connected!"); });

Does socket.io reconnect automatically?

In the first case, the Socket will automatically try to reconnect, after a given delay.


1 Answers

You should use the callback parameter while defining the event handler.

A typical implementation would be as follows:

Client side

var socket = io.connect('http://localhost'); socket.emit('set', 'is_it_ok', function (response) {     console.log(response); }); 

Server side

io.sockets.on('connection', function (socket) {     socket.on('set', function (status, callback) {         console.log(status);         callback('ok');     }); }); 

Now check the console on the server side. It should display 'is_it_ok'. Next check console on client side. It should display 'ok'. That's the confirmation message.

Update

A socket.io connection is essentially persistent. The following in-built functions let you take action based on the state of the connection.

socket.on('disconnect', function() {} ); // wait for reconnect socket.on('reconnect', function() {} ); // connection restored   socket.on('reconnecting', function(nextRetry) {} ); //trying to reconnect socket.on('reconnect_failed', function() { console.log("Reconnect failed"); }); 

Using the callback option shown above is effectively a combination of the following two steps:

socket.emit('callback', 'ok') // happens immediately 

and on the client side

socket.on('callback', function(data) {     console.log(data); }); 

So you don't need to use a timer. The callback runs immediately except if the connection has any of the following states - 'disconnect', 'reconnecting', 'reconnect_failed'.

like image 122
almypal Avatar answered Oct 18 '22 08:10

almypal