colyseus / colyseus-defold

⚔ Colyseus SDK for Defold Engine
https://docs.colyseus.io/getting-started/defold-client/
MIT License
60 stars 10 forks source link

Error on reconnecting with poor network connectivity #56

Closed baochungit closed 4 months ago

baochungit commented 4 months ago

When reconnecting, sometimes it raised this error and no return callback. What could it be?

2024-05-03 22:18:09.907 16112-16283/com.chungxa.kyhoang E/defold: ERROR:SCRIPT: HTTP request to 'http://10.57.22.125:2567/matchmake/reconnect/5dw-1BzKd?' failed (http result: -1  socket result: 0)
2024-05-03 22:18:09.911 16112-16229/com.chungxa.kyhoang E/defold: ERROR:SCRIPT: colyseus/http.lua:150: Expected object key string but found unexpected end of string at character 1080
    stack traceback:
      [C]:-1: in function decode
      colyseus/http.lua:150: in function <colyseus/http.lua:143>
endel commented 4 months ago

Hi @baochungit, this error looks suspicious as it indicates there was an error parsing the JSON body at http.lua:150.

However, if the server responded with content-type: application/json header it should've definitely returned a valid JSON body. Can you inspect the network to check what's the value being returned from this request?

baochungit commented 4 months ago

Can you inspect the network to check what's the value being returned from this request?

I'm afraid that I can not. Actually it was the first time I seen this error and it happened on my Android phone.

My guess is due to the poor network connectivity, the http request was failed (http result: -1 ?) after a certain timeout. Even so it still collected some header info and corrupted body and pass them to the request callback. If it's the case then relying on headers only will not safe enough. I may look into the http.request function of Defold to see how it works..

baochungit commented 4 months ago

Looking into this code https://github.com/defold/defold/blob/dev/engine/script/src/http_service.cpp#L288, I think it's worth to check response.status == 0 for failed requests.

endel commented 4 months ago

That makes sense, thanks for checking @baochungit, perhaps we should move this block before parsing the JSON then: https://github.com/colyseus/colyseus-defold/blob/master/colyseus/http.lua#L153-L155

This would likely fix:

+   if response.status == 0 then
+     return callback("offline")
+   end

    -- parse JSON response
    if response.headers['content-type'] and string.find(response.headers['content-type'], 'application/json') then
      data = json.decode(data)
    end

-    if not data and response.status == 0 then
-      return callback("offline")
-    end