minecraft-cc-tools/libs/net.lua
2024-05-21 22:34:50 +02:00

59 lines
1.4 KiB
Lua

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()
local serverRunning = true
local function stopServer()
serverRunning = false
end
rednet.host(QUERY_PROTO, hostname)
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
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 nil, 'hostname lookup error'
end
local sendOk = rednet.send(serverId, textutils.serialize(message))
if not sendOk then
return nil, 'rednet error'
end
local responseServerId, responseMessage = rednet.receive(QUERY_RESPONSE_PROTO, timeout)
if not responseServerId then
return nil, 'timeout'
end
return textutils.unserialize(responseMessage)
end
return net