Advertisement
fyrkantis

messengerServer.lua

Aug 3rd, 2024 (edited)
383
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. -- https://stackoverflow.com/a/7615129/13347795
  2. function split(input, maxSplits, sep)
  3.     if sep == nil then
  4.         sep = ";"
  5.     end
  6.     splits = {}
  7.     splitCount = 0
  8.     for str in string.gmatch(input, "([^"..sep.."]+)") do
  9.         if maxSplits ~= nil and splitCount > maxSplits then
  10.             splits[splitCount] = splits[splitCount]..sep..str
  11.         else
  12.             table.insert(splits, str)
  13.             splitCount = splitCount + 1
  14.         end
  15.     end
  16.     return splits
  17. end
  18.  
  19. function refresh()
  20.     h = fs.open("messages.txt", "r")
  21.     term.clear()
  22.     term.setCursorPos(1, 1)
  23.     repeat
  24.         line = h.readLine()
  25.         if line ~= nil and line ~= "" then
  26.             date, time, id, message = table.unpack(split(line, 3))
  27.             print(message)
  28.         end
  29.     until line == nil
  30.     h.close()
  31. end
  32.  
  33. write("Starting...")
  34. if not fs.exists("messages.txt") then
  35.     local h = fs.open("messages.txt", "w")
  36.     h.close()
  37. end
  38.  
  39. peripheral.find("modem", rednet.open)
  40.  
  41. local h = fs.open("messages.txt", "r")
  42. rednet.broadcast(h.readAll(), "response-messenger-backlog")
  43. h.close()
  44. refresh()
  45.  
  46. while true do
  47.     id, message, protocol = rednet.receive()
  48.     if protocol == "request-messenger-backlog" then
  49.         local h = fs.open("messages.txt", "r")
  50.         rednet.send(id, h.readAll(), "response-messenger-backlog")
  51.         h.close()
  52.     elseif protocol == "broadcast-messenger-message" then
  53.         local h = fs.open("messages.txt", "a")
  54.         h.writeLine(os.date("%F;%T;")..id..";"..message)
  55.         h.close()
  56.     end
  57.     refresh()
  58. end
  59.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement