View difference between Paste ID: vprpZUjZ and qctx4dbx
SHOW: | | - or go back to the newest paste.
1-
local default = "wss://osmarks.ml/ws/"
1+
local m = peripheral.find "modem"
2
3-
local ws, error, url
3+
local function prompt(what, default)
4
	write(what .. "> ")
5-
function connect()
5+
	local result = read()
6-
	ws, error = http.websocket(url)
6+
	if result == "" then 
7-
	if error then
7+
		print("Defaulted to", textutils.serialise(default))
8-
		print(error)
8+
		return default
9-
	else
9+
10-
		print "Connected"
10+
	return result
11
end
12
13
local protocol = prompt("Protocol", nil)
14-
repeat
14+
local sender = tonumber(prompt("Sender", os.getComputerID()))
15-
	write "URL> "
15+
local recipient = tonumber(prompt("Recipient", rednet.CHANNEL_BROADCAST))
16-
	url = read()
16+
17
m.open(rednet.CHANNEL_REPEAT)
18-
	if url == "" then
18+
19-
		print("Defaulted to", default)
19+
local function send(from, protocol, content, to)
20-
		url = default
20+
	local packet = {
21
		nMessageID = math.random( 1, 2147483647 ),
22
		nRecipient = to,
23-
	connect()
23+
		message = content,
24-
until ws
24+
		sProtocol = protocol,
25
	}
26-
function readWS()
26+
27
	m.transmit(to, from, packet)
28-
		print(ws.receive())
28+
	m.transmit(rednet.CHANNEL_REPEAT, from, packet)
29
end
30
31
local function receive()
32-
function send(msg)
32+
	local _, _, chan, replyChan, message = os.pullEvent "modem_message"
33-
	local ok = pcall(ws.send, msg)
33+
	return message.nRecipient, replyChan, message.message, message.sProtocol
34
end
35-
	if not ok then
35+
36-
		print "Disconnected"
36+
local function recvLoop()
37-
		connect()
37+
38-
		send(msg)
38+
		local recipient, sender, message, protocol = receive()
39
		local text = sender .. ">" .. recipient
40
		if protocol then text = text .. " (" .. protocol .. ")" end
41
		text = text .. " " .. textutils.serialise(message)
42-
function writeWS()
42+
		print(text)
43
	end
44-
		sleep(0.2) -- so response can arrive
44+
45
46-
		local input = read()
46+
local function sendLoop()
47-
		send(input)
47+
48
		write "|> "
49
		local msg = read()
50
		send(sender, protocol, msg, recipient)
51-
parallel.waitForAll(writeWS, readWS)
51+
52
end
53
54
parallel.waitForAll(sendLoop, recvLoop)