5

If the client emit some msg to the server, is there any way for client to know if this emit is failed or not ?

I think it my be some callback like :

socket.emit("test",dataToSend,function(err){ });
Hohoho
  • 53
  • 1
  • 3
  • How/where would it fail? – Bergi Feb 24 '15 at 16:06
  • I think the only way for an emit to fail is when the connection is lost, and I am sure there is something like `socket.on('disconnect')`... – Robert Rossmann Feb 24 '15 at 16:22
  • 1
    @Bergi - there are a number of possible failure modes: outbound buffers could be full, internet connection could be lost, but socket hasn't noticed the failure yet, server could be not responding, server inbound buffers could be full, connection to server could be down but socket hasn't noticed yet, etc... – jfriend00 Feb 24 '15 at 21:50

2 Answers2

0

You can configure the server to listen for test event, and emit back a test succeeded event.

socket.on("test", function(data) {
    socket.emit("test succeeded", data);
});

This way you can listen for successfully received test events like so:

socket.on('test succeeded', function(data) {});

Update

If you want to be notified on errors, send your function as the third argument.

// client
socket.emit("test", dataToSend, function(err, success) {
});

Then, on the server

socket.on("test", function(dataReceived, callback) {
});

Acknowledgement functions documentation

Muhammad Reda
  • 26,379
  • 14
  • 93
  • 105
  • 9
    But how about if the emit failed? For example, the server is closed when the client emit the msg to it, then the client won't receive any msg from the server because the server is not working. – Hohoho Feb 24 '15 at 16:09
  • It won't work. refer https://stackoverflow.com/questions/52676171/callbacks-are-not-supported-when-broadcasting – Malavan Feb 22 '19 at 06:10
0

on server

io.on('connect', (socket) => {
    socket.on('join-room', ( user, handleError ) => {
         //process data with user
         let error = 'can not find user'
         return handleError(error )
    }
}

on client

socket.emit('join-room', user, error => {
    console.log(error) //error from Server is here
}
sun1211
  • 1,219
  • 10
  • 15