Advertisement
abstract_abstract

dns_server.lua

Oct 9th, 2024
260
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.02 KB | None | 0 0
  1. rednet.open("right")
  2.  
  3. print("DNS server started")
  4.  
  5. local dnsTable = {}
  6.  
  7.  
  8. local function saveToFile(filename)
  9.     local file = fs.open(filename, 'w')
  10.     if file then
  11.         file.write(textutils.serialize(dnsTable))
  12.         file.close()
  13.         print("DNS table saved to " .. filename)
  14.     else
  15.         print("Error: unable to open file for saving")
  16.     end
  17. end
  18.  
  19.  
  20. local function loadFromFile(filename)
  21.     if fs.exists(filename) then
  22.         local file = fs.open(filename, 'r')
  23.         if file then
  24.             local content = file.readAll()
  25.             dnsTable = textutils.unserialise(content) or {}
  26.             file.close()
  27.             print("DNS table loaded from " .. filename)
  28.         else
  29.             print("Error: Unable to open file for loading")
  30.         end
  31.     else
  32.         print("No existing DNS table found, starting fresh")
  33.     end
  34. end
  35.  
  36.  
  37. local function registerComputer(name, id)    
  38.     dnsTable[id] = name
  39.     print("Registation successful")
  40.     print("PC: " .. name .. " ID: " .. id)
  41.  
  42.     saveToFile("dns_table.txt")
  43.  
  44.     return true
  45. end
  46.  
  47.  
  48. local function getAllComputers()
  49.     return dnsTable
  50. end
  51.  
  52.  
  53. loadFromFile("dns_table.txt")
  54.  
  55.  
  56. while true do
  57.     local senderID, message, protocol = rednet.receive()
  58.     if type(message) == "string" then
  59.         local data = textutils.unserialize(message)
  60.         if protocol == "dns_register" then
  61.             if data and data.name and data.id then
  62.                 if registerComputer(data.name, data.id) then
  63.                     rednet.send(senderID, "Registation has been successful", "dns_ack")
  64.                 else
  65.                     rednet.send(senderID, "Registration failed: Name already registered", "dns_ack")
  66.                 end
  67.             end    
  68.         elseif protocol == "dns_list" then
  69.             local allComputers = getAllComputers()
  70.             local listMessage = textutils.serialize(allComputers)
  71.             rednet.send(senderID, listMessage, "dns_list_response")
  72.         end    
  73.         sleep(0,5)
  74.     end
  75. end
  76.  
  77.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement