I’ve decided to move my asynchronous WebSocket module from DefNet to a separate repo. The module has also received a number of improvements and the underlying lua-websocket project has been updated. The new version should in theory also work with secure WebSockets thanks to the use of LuaSec. Defold-WebSocket is currently used in the Defold client of the Colyseus game server and client lib.
Check the asset page for details and an example of how to use the module:
I noticed the secure websocket does not work for HTML5 version, it indeed works for other kinds of bundles.
For HTML5 version, there is an error message like “MyProject.js:1 WebSocket connection to ‘ws://domain:port/’ failed: Error during WebSocket handshake: net::ERR_INVALID_HTTP_RESPONSE”
In fact, I specified the target url '‘wss://domain:port/’ instead of ‘ws://domain:port/’. I don’t know if this problem is easy to fix since I already get openssl / luasec extension built with emscripten.
Hold on, for HTML5 there’s no use of LuaSec. Emscripten will automatically upgrade socket connections to Websockets. That’s why the Defold-Websocket project has two code paths in many places to for instance skip the handshake and socket upgrade etc. The readme should documentat thus fairly well.
With an empty clean project, and this code based on the example page:
local client_async = require "websocket.client_async"
function init(self)
self.ws = client_async()
self.ws:on_connected(function(ok, err)
if ok then
print("Connected")
msg.post("#", "acquire_input_focus")
else
print("Unable to connect", err)
end
end)
self.ws:on_disconnected(function()
print("Disconnected")
end)
self.ws:connect("ws://localhost:8080")
end
function update(self, dt)
self.ws:step()
end
It prints the message properly if the server is running. But if the server is not running, the “Unable to connect” does not get printed.
I also tried Colyseus, and it’s the same thing. The “on error” event there also doesn’t get triggered.
I tried it on the latest editor 1.2.142, but I’ve never been successful in older versions either. I also tried html5 build, I do get a websocket error there.
However, this error is not captured in code (i.e. can’t connect error doesn’t even get printed in the console).
How do I capture this connection refused properly in code, so I can display an error message properly? Potential workaround is to have a timeout e.g. if after 2 seconds I am still not connected, then I can assume something is wrong with the connection. But I am hoping this is something the extension is capturing properly, and I just don’t know how to make it work.
I am using Windows 10. I don’t have access to a Mac right now, but I will try over there when I get the chance. Actually, I am also not getting the Disconnected event (if I terminate the server while the Defold client is connected).
For Colyseus, yes my set-up is the same (call to connect is after the listeners have been registered), but sadly the same results.