Search code examples
socketstcprequestresponsemessenger

how to implement request response in a tcp connection?


I'm working on a messenger communicating over tcp sockets, that are kept alive until something happens, then the client will have to reconnect.

All the requests are sent over one alive connection, which raises my question.

How shall I map a response from server to a specific request from client?

Example:

1 - Client sends a request to update username:

{"action":"edit_username", data: "new_username":"blablabla"}

2 - Server sends an update to inform the client about a new received message:

{"update":{"type":"new_message", "text":"Hi"}}

3 - Server responds to user's request to update username:

{"ok": true, "message":"success"}

Now, what are the ways to know that the 3rd item is the response to the 1st one?


Solution

  • I ended up defining message id for each message on the client side, then on the server I set "response_to_message_id" value according to the message id. This way, on the client I add "message_id"s, that need responses, to an array and after making each request, I check that array in the loop for a few seconds to find out if there's a message from server that has "response_to_message_id" equal to current request's message_id, and if there is, I process the response.

    Hope it helps others.