local modem = peripheral.find("modem") local SERVER_PORT = 100 local CLIENT_PORT = 101 local function log(msg) print("[Server]: " .. tostring(msg)) end local function broadcast(message) if modem then modem.transmit(CLIENT_PORT, SERVER_PORT, message) end end local function handleMessage(event, side, channel, replyChannel, message, distance) if type(message) == "table" then if message.type == "join" then log(message.username .. " connected.") broadcast({ type = "system", content = message.username .. " joined the chat." }) elseif message.type == "leave" then log(message.username .. " disconnected.") broadcast({ type = "system", content = message.username .. " left the chat." }) elseif message.type == "chat" then log(message.username .. ": " .. message.content) broadcast({ type = "chat", username = message.username, content = message.content }) end end end local function listenLoop() if not modem then log("No modem found!") return end modem.open(SERVER_PORT) log("Listening on port " .. SERVER_PORT) while true do local eventData = {os.pullEvent("modem_message")} -- event, side, channel, replyChannel, message, distance if eventData[3] == SERVER_PORT then handleMessage(table.unpack(eventData)) end end end local function main() parallel.waitForAll(listenLoop) end return { main = main }