mirror of
https://github.com/lune-org/lune.git
synced 2024-12-12 04:50:36 +00:00
Add examples for web socket servers & clients
This commit is contained in:
parent
d50df04d09
commit
b302543502
2 changed files with 66 additions and 0 deletions
35
.lune/examples/websocket_client.luau
Normal file
35
.lune/examples/websocket_client.luau
Normal file
|
@ -0,0 +1,35 @@
|
|||
--> A basic web socket client communicates with an echo server
|
||||
|
||||
local URL = "wss://demo.piesocket.com/v3/"
|
||||
|
||||
-- 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
|
||||
|
||||
task.delay(10, function()
|
||||
warn("Example did not complete in time, exiting...")
|
||||
process.exit(1)
|
||||
end)
|
||||
|
||||
-- Send one message per second and time it
|
||||
|
||||
for i = 1, 5 do
|
||||
local start = os.clock()
|
||||
socket.send(tostring(1))
|
||||
local response = socket.next()
|
||||
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...")
|
||||
socket.close()
|
||||
|
||||
print("Done! 🌙")
|
31
.lune/examples/websocket_server.luau
Normal file
31
.lune/examples/websocket_server.luau
Normal file
|
@ -0,0 +1,31 @@
|
|||
--> A basic web socket server that echoes given messages
|
||||
|
||||
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
|
||||
|
||||
-- Run the server on port 8080
|
||||
|
||||
local handle = net.serve(PORT, {
|
||||
handleWebSocket = function(socket)
|
||||
print("Got new web socket connection!")
|
||||
repeat
|
||||
local message = socket.next()
|
||||
if message ~= nil then
|
||||
socket.send("Echo\n" .. message)
|
||||
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
|
||||
|
||||
task.delay(2, function()
|
||||
print("Shutting down...")
|
||||
task.wait(1)
|
||||
handle.stop()
|
||||
end)
|
Loading…
Reference in a new issue