javascriptasynchronouswebsocket

Javascript websocket asynchronous no sleep


I am from a firmware background and primarily write code in normal procedural C.

Currently I need to get a Web Browser to connect to some hardware via a dedicated TCP socket and exchange data in a custom protocol format. We have elected to go the Websockets route as this technology works on new phones,PC's and tablets.

My problem is that Javascript has no true Sleep() function. Normally we would do something like this:

  1. send a message.
  2. Sleep whilst the hardware processing the message.
  3. Get the response and continue running program.

For example, I would like to save some data to hardware.

  1. send data in protocol.
  2. get the response confirming the hardware saved the data.
  3. if successful send message A else send some message B.

The problem is step 3 cannot be done since there is no Sleep. I have read about the setTimeoutfunction() but this does not solve my problem. It seems to messy to have the callback event handle each received packet and jumping to different functions. Also, if i had a whole lot of sends in a while loop, this seems impossible with the callback functions?

I understand my approach may be wrong but can anybody explain to me how to adjust my reasoning to handle this situation?

Any comments or suggestion will be appreciated.

Thanks,


Solution

  • You shouldn't use sleep to wait for Websocket response even if there was one in javascript. Using sleep would hang your whole site in wait for socket response. By hang I, for example mean, no interaction from user.

    To deal with endless callbacks You need to do some design first, not just throw them here and there.

    Canonical way of doing this is to register one handler for (Web)socket which is called when server sends You a message. Your application remembers internally it's state (read about state machines) and knows what to do with this message, in this point of execution it currently is.

    BTW. If Your flow is only as You've written to ask server and wait for response, please consider using simple AJAX. WebSocket is designed to allow server to push messages to receiver when it(server) decides to, not only to answer explicit request. AJAX was designed for this use-case and you can call it synchronously so make Your program linear even without sleeps ;)