2023-02-12 14:25:17 +00:00
|
|
|
--> A basic web socket server that echoes given messages
|
|
|
|
|
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
|
|
|
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
|
|
|
|
|
2023-02-12 16:30:15 +00:00
|
|
|
-- Run the server on port 8080, if we get a normal http request on
|
|
|
|
-- the port this will respond with 426 Upgrade Required by default
|
2023-02-12 14:25:17 +00:00
|
|
|
|
|
|
|
local handle = net.serve(PORT, {
|
|
|
|
handleWebSocket = function(socket)
|
|
|
|
print("Got new web socket connection!")
|
|
|
|
repeat
|
|
|
|
local message = socket.next()
|
|
|
|
if message ~= nil then
|
2023-02-12 17:24:55 +00:00
|
|
|
socket.send("Echo - " .. message)
|
2023-02-12 14:25:17 +00:00
|
|
|
end
|
|
|
|
until message == nil
|
|
|
|
print("Web socket disconnected.")
|
|
|
|
end,
|
|
|
|
})
|
|
|
|
|
|
|
|
print(`Listening on port {PORT} 🚀`)
|
|
|
|
|
|
|
|
-- Exit our example after a small delay, if you copy this
|
|
|
|
-- example just remove this part to keep the server running
|
|
|
|
|
2023-02-12 17:24:55 +00:00
|
|
|
task.delay(10, function()
|
2023-02-12 14:25:17 +00:00
|
|
|
print("Shutting down...")
|
|
|
|
task.wait(1)
|
|
|
|
handle.stop()
|
2023-02-12 17:24:55 +00:00
|
|
|
task.wait(1)
|
2023-02-12 14:25:17 +00:00
|
|
|
end)
|