Files
nova-corp/programs/chat.lua
2025-12-12 17:14:05 -05:00

70 lines
1.9 KiB
Lua

local modem = peripheral.find("modem")
local speaker = require("speaker-driver")
local SERVER_PORT = 100
local CLIENT_PORT = 101
local username = os.getComputerLabel() or ("User" .. os.getComputerID())
local function start()
if modem then
modem.open(CLIENT_PORT)
modem.transmit(SERVER_PORT, CLIENT_PORT, { type = "join", username = username })
end
print("Chat program started as " .. username)
end
local function stop()
if modem then
modem.transmit(SERVER_PORT, CLIENT_PORT, { type = "leave", username = username })
modem.close(CLIENT_PORT)
end
print("Chat program stopped.")
end
local function restart()
stop()
start()
end
local function receiveLoop()
while true do
local event, side, channel, replyChannel, message, distance = os.pullEvent("modem_message")
if channel == CLIENT_PORT and type(message) == "table" then
local x, y = term.getCursorPos()
term.setCursorPos(1, y)
term.clearLine()
if message.type == "system" then
print("[System] " .. message.content)
speaker.play("notification")
elseif message.type == "chat" then
print(message.username .. ": " .. message.content)
speaker.play("notification")
end
write("> ")
end
end
end
local function sendLoop()
while true do
write("> ")
local input = read()
if modem then
modem.transmit(SERVER_PORT, CLIENT_PORT, { type = "chat", username = username, content = input })
end
end
end
local function main()
if not modem then
print("No modem attached")
while true do os.pullEvent() end
end
parallel.waitForAny(receiveLoop, sendLoop)
end
return { start = start, stop = stop, restart = restart, main = main }