Node.js + socket.io return data on event

I'm currently building a small chat.

When someone hits enter, it should submit the message to the server and return some status info if inserting was successful.

Is there a way to return some data on every event or do I have to initiate another send from the server to notifiy the client about the status?

Client

$('textarea').keypress(function(e) {

    if(e.which == 13) {

                var msg = $.trim(this.value);

                if(msg.length > 0) {

                        socket.send(msg, function() {

                             // Here I need to have some result
                             // returned by the server to notify the user
                             // if everything went fine
                             //this.value = '';
                        });
                }

                return false;
        }
});

Server

socket.on('message', function() {

        db.query("INSERT INTO chat (message, ip, time) VALUES (?, INET_ATON(?), NOW())", [msg, socket.handshake.headers['x-forwarded-for'] || socket.handshake.address.address], function(error) {

                if(!error) {
                        io.sockets.send(msg);
                } else {
                        console.log(error);
                }

        });
});

I ran into this issue recently. My solution was to put a command ID into every message. I built a little function to make an ID on the client side (here). So the flow looks like this:

Client

  • when the user does something that needs to be saved:
  • generate an ID for the command
  • generate an object that describes the command
  • send the command over the socket to the server

Server

  • receive the command message
  • apply the command (database etc)
  • if the command succeeds, send the command ID back to the client over the socket with a "command complete" message type

Client

  • receive the command complete message
  • mark that command as "done" on the client side

Code for the server side step:

socket.on 'du', (msg) =>
  @saveData(msg, ->
    # broadcast to other users if needed
    socket.emit('cc', msg.data.commandId)
  )