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.

64 lines
1.6 KiB

local event = event or require("event")
local component = comonent or require("component")
local modem = component.modem
local Server = {}
Server.__index = Server
setmetatable(Server, {
__call = function (cls, ...) return cls.new(...) end,
})
-- Creates a new server object listening on a port
-- Optionally include a "marker" string to find event listener
function Server.new(port, marker)
local self = setmetatable({}, Server)
self.port = port
self.marker = marker
self.handlers = setmetatable({}, { __index = function() return function() end end })
-- Remove any handlers with this marker
if marker ~= nil then
for i, _ in pairs(event.handlers) do
if marker == event.handlers[i].marker then
event.cancel(i)
end
end
end
self.eventID = event.listen("modem_message", function (...)
-- event type, local addr, remote addr, port, distance, msg
local tmp = {...}
-- Filter out messages coming from the wrong port
if tmp[4] ~= self.port then return end
-- Forward message to the correct handler
self.handlers[tmp[6]](...)
end)
modem.open(self.port)
return self
end
-- Adds a new endpoint event handler
function Server:handle(endpoint, f)
self.handlers[endpoint] = f
end
function Server:close()
event.cancel(self.eventID)
modem.close(self.port)
end
--[[
function Server.example()
Server.handlers["/example"] = function (pkt)
modem.send(pkt.raddr, pkt.port, "hello world")
end
end
]]
return Server