Advertisement
abstract_abstract

dns_server.lua

Oct 8th, 2024
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.03 KB | None | 0 0
  1. rednet.open("right")
  2.  
  3. print("DNS server started")
  4.  
  5. local dnsTable = {}
  6.  
  7.  
  8. local function saveToFile(fulename)
  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 loadlFromFile(filename)
  21.     if fs.exists(filename) then
  22.         local file = fs.open(fileopen, '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.     if dnsTable[name] then
  39.         print("Registration failed: Name already registred")
  40.         return false
  41.     end
  42.    
  43.     dnsTable[name] = id
  44.     print("Registation successful")
  45.     print("PC: " .. name .. " ID: " .. id)
  46.  
  47.     saveToFile("dns_table.txt")
  48.  
  49.     return true
  50. end
  51.  
  52.  
  53. local function getAllComputers()
  54.     return dnsTable
  55. end
  56.  
  57.  
  58. loadFromFile("dns_table.txt")
  59.  
  60.  
  61. while true do
  62.     local senderID, message, protocol = rednet.receive()  
  63.     local data = textutils.unserialise(message)
  64.    
  65.     if protocol == "dns_register" then
  66.         if data and data.name and data.id then
  67.             if registerComputer(data.name, data.id) then
  68.                 rednet.send(senderID, "Registation has been successful", "dns_ack")
  69.             else
  70.                 rednet.send(senderID, "Registration failed: Name already registered", "dns_ack")
  71.             end
  72.         end    
  73.     elseif protocol == "dns_list" then
  74.         local allComputers = getAllComputers()
  75.         local listMessage = textutils.serialize(allComputers)
  76.         rednet.send(senderID, listMessage, "dns_list_response")
  77.     end    
  78. end
  79.  
  80.  
  81.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement