Max Bumaye
Max Bumaye

Reputation: 1009

Correctly capture an error Socket.io

I am building a simple chat. I am using the websocket lib socket.io because it has a great server/client implementation.

My client is on mobile and therefore has a very unstable network connection. I have read something about acknowledgment functions which could be passed with an emit, to execute code once the socket "transaction" is done. But building an error handling on top of that would be very uggly.

I have also read about the .on('error' implementation that catches errors.

The problem here is: how do I seperate between an unsuccessfuly sent message (.emit) and a temporarily lost socketconnection. I dont care about losing the socketconnection because i set it up to reconnect once its lost.

I hope my situation got clear. Thanks in advance.

EDIT:

What I am looking for is something like this on the clientside:

socket.on('error', function(data){
   alert(data.emitData.msg+' could not be sent: '+data.emitID);
});

I am going to start taking a closer look at the API myself in the meantime

Upvotes: 0

Views: 997

Answers (1)

jfriend00
jfriend00

Reputation: 707198

Message acknowledgement is covered here in the socket.io docs. Here's the relevant part of that docs:

Sometimes, you might want to get a callback when the client confirmed the message reception.

To do this, simply pass a function as the last parameter of .send or .emit. What’s more, when you use .emit, the acknowledgement is done by you, which means you can also pass data along:

Server (app.js)

var io = require('socket.io').listen(80);

io.sockets.on('connection', function (socket) {
  socket.on('ferret', function (name, fn) {
    fn('woot');
  });
});

Client (index.html)

<script>
  var socket = io(); // TIP: io() with no args does auto-discovery
  socket.on('connect', function () { // TIP: you can avoid listening on `connect` and listen on events directly too!
    socket.emit('ferret', 'tobi', function (data) {
      console.log(data); // data will be 'woot'
    });
  });
</script>

And, another example shown here: Acknowledgment for socket.io custom event

Upvotes: 2

Related Questions