OpenComputers Von Neumann Machine Programs
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

63 lines
1.6 KiB

  1. local event = event or require("event")
  2. local component = comonent or require("component")
  3. local modem = component.modem
  4. local Server = {}
  5. Server.__index = Server
  6. setmetatable(Server, {
  7. __call = function (cls, ...) return cls.new(...) end,
  8. })
  9. -- Creates a new server object listening on a port
  10. -- Optionally include a "marker" string to find event listener
  11. function Server.new(port, marker)
  12. local self = setmetatable({}, Server)
  13. self.port = port
  14. self.marker = marker
  15. self.handlers = setmetatable({}, { __index = function() return function() end end })
  16. -- Remove any handlers with this marker
  17. if marker ~= nil then
  18. for i, _ in pairs(event.handlers) do
  19. if marker == event.handlers[i].marker then
  20. event.cancel(i)
  21. end
  22. end
  23. end
  24. self.eventID = event.listen("modem_message", function (...)
  25. -- event type, local addr, remote addr, port, distance, msg
  26. local tmp = {...}
  27. -- Filter out messages coming from the wrong port
  28. if tmp[4] ~= self.port then return end
  29. -- Forward message to the correct handler
  30. self.handlers[tmp[6]](...)
  31. end)
  32. modem.open(self.port)
  33. return self
  34. end
  35. -- Adds a new endpoint event handler
  36. function Server:handle(endpoint, f)
  37. self.handlers[endpoint] = f
  38. end
  39. function Server:close()
  40. event.cancel(self.eventID)
  41. modem.close(self.port)
  42. end
  43. --[[
  44. function Server.example()
  45. Server.handlers["/example"] = function (pkt)
  46. modem.send(pkt.raddr, pkt.port, "hello world")
  47. end
  48. end
  49. ]]
  50. return Server