Advertisement
Elkemental

cctweaked base ws connection.lua

Jan 19th, 2025 (edited)
27
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.10 KB | None | 0 0
  1. local monitor = peripheral.find("monitor");
  2. monitor.clear();
  3. monitor.setCursorPos(1,1);
  4.  
  5. local function printM(string)
  6.     term.redirect(monitor);
  7.     print(string);
  8.     term.redirect(term.native());
  9. end
  10.  
  11.  
  12. local ws;
  13.  
  14. local function init(url)
  15.     if ws then
  16.         ws.close();
  17.         ws = nil;
  18.     end
  19.  
  20.     local connection = http.websocket(url);
  21.  
  22.     if connection then
  23.         ws = connection;
  24.         print("Connection opened!");
  25.     else
  26.         print("Failed to connect to: " .. url);
  27.     end
  28. end
  29.  
  30. local function cleanup()
  31.     print("Exiting...");
  32.     ws.close();
  33.     ws = nil;
  34.     shell.exit()
  35. end
  36.  
  37. init("ws://localhost:8080");
  38.  
  39. while true do
  40.     local event = os.pullEventRaw(); if event == "terminate" then print("Program terminated"); cleanup(); break; end;
  41.  
  42.     local message = ws.receive();
  43.     if message then
  44.         if message == "close" then
  45.             print("Connection closed.");
  46.             cleanup();
  47.             break;
  48.         end
  49.  
  50.         printM(message);
  51.     else
  52.         print("Connection closed.");
  53.         cleanup();
  54.         break;
  55.     end
  56. end
  57.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement