local DEFAULT_TIMEOUT = 2 local QUERY_PROTO = 'trap/query' local QUERY_RESPONSE_PROTO = 'trap/query:response' local net = {} local function assertRednetIsOpened() if not rednet.isOpen() then error('rednet should be enabled with rednet.open(modemName)') end end net.listenQuery = function(hostname, processQueryMessage) assertRednetIsOpened() rednet.host(QUERY_PROTO, hostname) local serverRunning = true local function stopServer() serverRunning = false end while serverRunning do local computerId, message = rednet.receive(QUERY_PROTO) local responseMessage = processQueryMessage(textutils.unserialize(message), computerId, stopServer) rednet.send(computerId, textutils.serialize(responseMessage), QUERY_RESPONSE_PROTO) end -- in case we decide to exit the loop in the future rednet.unhost(QUERY_PROTO) end net.sendQuery = function(hostname, message, timeout) timeout = timeout or DEFAULT_TIMEOUT assertRednetIsOpened() local serverId = rednet.lookup(QUERY_PROTO, hostname) if not serverId then return false, 'hostname lookup error' end local sendOk = rednet.send(serverId, textutils.serialize(message)) if not sendOk then return false, 'rednet error' end local responseServerId, responseMessage = rednet.receive(QUERY_RESPONSE_PROTO, timeout) if not responseServerId then return false, 'timeout' end return textutils.unserialize(responseMessage) end return net