ShahiM
ShahiM

Reputation: 3268

Wrapping my head around Socket.io Client API

Normally, when we use HTTP requests, we have a specific set of methods/callbacks that would be called when the request succeeds/fails. Each connection request could have its own callback methods, which made structuring of code very easy.

So now that I am trying out Socket.io for a new project, I got all confused. For instance, you emit a message into the socket connection and you're done. no callbacks there. There is no easy way I can know if that actually succeeded or not I've managed to simulate a callback by writing this method:

public void emitRequest(final String event, JSONObject data, final emitResponseListener pListener)
{
  mSocket.on(event+"_resp", new Listener() {
    @Override
    public void call(final Object... args) {
      ((Activity)c).runOnUiThread(new Runnable() {
        @Override
        public void run() {
          JSONObject data = (JSONObject) args[0];
            if (pListener!=null)
            {
              pListener.onResponseRecieved(data);
            }
        }
      });
    }
  });
  mSocket.emit(event,data);
}

This method listens for a event_resp message from the server after emitting an event. But thats as far as I've got. I have no clue as to how to handle errors for specific emits, so as to update the UI or inform the user .etc.

Sure, there are callback events for the Socket but those are impossible to wire up into the apps flow.

So does anybody know a way to achieve this? I searched a lot but couldn't find anything. I'm using Java Client but generalized answers for any client API are welcome.

Upvotes: 1

Views: 215

Answers (1)

Kuf
Kuf

Reputation: 17846

You have to change your view - instead of callbacks think about events, and base your design accordingly.

When you make a request to the socket server, generate a unique token. Send the token to the server and have the server send it back with the request response. Using the token you can register a callback that will fire for event matching the request response event and this token.

This way you can execute the calls one after another.

To Cover cases where the server did not return a response, we use timeouts of 30 seconds. About 99.9% of the times we didn't get a response happened due to socket disconnection, so the socket error callback handled that after successful reconnection, without reaching the timeout.

Upvotes: 1

Related Questions