Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local component = require("component")
- local modem = component.modem
- local fs = require("filesystem")
- local event = require("event")
- local serial = require("serialization")
- require("functions") --helper functions
- --These need to be the same between the client and server
- local portNum = 462
- local msgDelim = "[:|:]"
- --This one can be different from client / server
- local programDir = "programs/"
- if not fs.isDirectory("programs") then
- fs.makeDirectory("programs")
- end
- function getFileList()
- local files = fs.list("programs/")
- local out = {}
- for file in files do
- if not fs.isDirectory(file) then
- out[fs.name(file)] = fs.lastModified(file)
- end
- end
- end
- function getFile(file)
- local fl = io.open(file, "r")
- local out = ""
- local buffer = ""
- while true do
- buffer = fl:read(1024)
- if buffer == nil then break end
- out = out .. buffer
- end
- fl:close()
- return out
- end
- function putFile(file, data)
- local fl = io.open(file, "w")
- local out = fl:write(data) --get the output in case it fails
- fl:close()
- return out
- end
- function handleClient(localAddress, remoteAddress, port, distance, message)
- if(port ~= portNum) then return end
- local arg = explode(msgDelim, message)
- if arg[1] == "getFileList" then
- modem.send(remoteAddress, portNum, "fileList" .. msgDelim .. serial.serialize(getFileList()))
- elseif arg[1] == "getFile" then
- local file = programDir .. fs.name(arg[2]) --make sure they don't try and get files elsewhere
- if fs.exists(file) and not fs.isDirectory(file) then
- modem.send(remoteAddress, portNum, "putFile" .. msgDelim .. arg[2] .. msgDelim .. getFile(file))
- else
- modem.send(remoteAddress, portNum, "error" .. msgDelim .. "Invalid file.")
- end
- elseif arg[1] == "putFile" then
- local file = programDir .. fs.name(arg[2]) --make sure they don't try and put files elsewhere
- local marg = explode(msgDelim,message,2) --only split the first two(command, file, then code)
- local out = putFile(file, marg[3])
- local ret = "success"..msgDelim.."Successfully saved file"
- if not out then
- ret = "error"..msgDelim.."Failed to save file"
- end
- modem.send(remoteAddress, portNum, ret)
- end
- end
- local args = {...}
- if(#args < 1) then
- print("Usage: fileserver [start/stop]")
- else
- if args[1] == "start" then
- event.listen("modem_message", handleClient)
- elseif args[1] == "stop" then
- event.ignore("modem_message", handleClient)
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement