diff --git a/.lune/examples/websocket_client.luau b/.lune/examples/websocket_client.luau new file mode 100644 index 0000000..5be1b8a --- /dev/null +++ b/.lune/examples/websocket_client.luau @@ -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! 🌙") diff --git a/.lune/examples/websocket_server.luau b/.lune/examples/websocket_server.luau new file mode 100644 index 0000000..89a4efb --- /dev/null +++ b/.lune/examples/websocket_server.luau @@ -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)