Reconnect WebSocket client connection on no response

Viewed 47

I have a lot of async connections to a WebSocket server. After a while, the server stops responding and the script just waits on response. I have to dockerize and deploy the script, so the only way to reset the connection is to run the docker image again.

The ideal solution would be something like a keyword argument to WebSockets.open. The code looks like:

map(container) do item
   @async begin
       WebSockets.open(url) do ws 
          payload = generatepayload(item)
          if writeguarded(ws, JSON3.write(payload))
              while isopen(ws)
                 data, success = readguarded(ws)
                 ### process data 
              end
           end
       end
    end
end

But any solution where I just have to write julia code would work.

1 Answers

WebSockets. jl's readguarded() allows a timeout read error exception to be ignored. As long as your socket read has a reasonable timeout (it should) handling the read failure yourself may help, since this could give you a new websocket connection with the server. for example:

map(container) do item
   @async while true
       try
           WebSockets.open(url) do ws  # reopens the websocket on while loop
              payload = generatepayload(item)
              if writeguarded(ws, JSON3.write(payload))
                  while isopen(ws)
                     data, success = read(ws)
                     ### process data 
                  end
              end
           end
       catch y
           @debug y  # log something here
           maybe check server some other way here and break if offline
       end
    end
end
Related