2023-02-12 17:24:55 +00:00
|
|
|
--> A basic web socket client that communicates with an echo server
|
2023-05-14 21:16:58 +01:00
|
|
|
|
|
|
|
local net = require("@lune/net")
|
|
|
|
local process = require("@lune/process")
|
|
|
|
local task = require("@lune/task")
|
2023-02-12 14:25:17 +00:00
|
|
|
|
2023-02-12 17:24:55 +00:00
|
|
|
local PORT = if process.env.PORT ~= nil and #process.env.PORT > 0
|
|
|
|
then assert(tonumber(process.env.PORT), "Failed to parse port from env")
|
|
|
|
else 8080
|
|
|
|
|
|
|
|
local URL = `ws://127.0.0.1:{PORT}`
|
2023-02-12 14:25:17 +00:00
|
|
|
|
|
|
|
-- Connect to our web socket server
|
|
|
|
|
|
|
|
local socket = net.socket(URL)
|
|
|
|
|
|
|
|
print("Connected to echo web socket server at '" .. URL .. "'")
|
|
|
|
print("Sending a message every second for 5 seconds...")
|
|
|
|
|
|
|
|
-- Force exit after 10 seconds in case the server is not responding well
|
|
|
|
|
2023-02-12 17:24:55 +00:00
|
|
|
local forceExit = task.delay(10, function()
|
2023-02-12 14:25:17 +00:00
|
|
|
warn("Example did not complete in time, exiting...")
|
|
|
|
process.exit(1)
|
|
|
|
end)
|
|
|
|
|
|
|
|
-- Send one message per second and time it
|
|
|
|
|
2023-03-22 15:40:43 +00:00
|
|
|
for _ = 1, 5 do
|
2023-02-12 14:25:17 +00:00
|
|
|
local start = os.clock()
|
2024-10-17 10:27:32 +01:00
|
|
|
socket:send(tostring(1))
|
|
|
|
local response = socket:next()
|
2023-02-12 14:25:17 +00:00
|
|
|
local elapsed = os.clock() - start
|
|
|
|
print(`Got response '{response}' in {elapsed * 1_000} milliseconds`)
|
|
|
|
task.wait(1 - elapsed)
|
|
|
|
end
|
|
|
|
|
|
|
|
-- Everything went well, and we are done with the socket, so we can close it
|
|
|
|
|
|
|
|
print("Closing web socket...")
|
2024-10-17 10:27:32 +01:00
|
|
|
socket:close()
|
2023-02-12 14:25:17 +00:00
|
|
|
|
2023-02-12 17:24:55 +00:00
|
|
|
task.cancel(forceExit)
|
2023-02-12 14:25:17 +00:00
|
|
|
print("Done! 🌙")
|