ludic/packages/ludic.net/punch.ludic

53 lines
2.2 KiB
Text

# punch.ludic - the host sends a few packets to each new guest's outside address, so its router
# expects the guest, while the guest's hello goes the other way: both routers have seen traffic
# go out, so the replies come in
@alloc_ok("once per guest punched for")
function net__new_guest(net_st: mut NetState, pub: string, local: string) -> void {
let key = `{pub}|{local}`
for i in 0 .. len(net_st.net__seen) { if net_st.net__seen[i] == key { return } }
push(net_st.net__seen, key)
net__log(`room {net_st.net__room}: a guest at {pub} / {local}`)
if len(pub) > 0 and net_parse_code(net_st, pub) { net__punch_add(net_st, net_st.net__code_ip, net_st.net__code_port) }
if net_parse_code(net_st, local) { net__punch_add(net_st, net_st.net__code_ip, net_st.net__code_port) }
}
@alloc_ok("once per guest punched for")
function net__punch_add(net_st: mut NetState, ip: int, port: int) -> void {
if net_st.net__punch_ip == null {
net_st.net__punch_ip = words(16)
net_st.net__punch_port = words(16)
net_st.net__punch_left = words(16)
for k in 0 .. 16 { net_st.net__punch_left[k] = 0 }
}
for k in 0 .. 16 {
if net_st.net__punch_left[k] > 0 { continue }
net_st.net__punch_ip[k] = ip
net_st.net__punch_port[k] = port
net_st.net__punch_left[k] = 10
return
}
}
# twice a second while a guest is new: a packet the guest's side ignores, which is the point
function net__punch_tick(net_st: mut NetState, dt: float) -> void {
if net_st.net__punch_ip == null { return }
net_st.net__punch_t = net_st.net__punch_t - dt
if net_st.net__punch_t > 0.0 { return }
net_st.net__punch_t = 0.5
if net_st.net__punch_b == null {
@alloc_ok("once: the punch's four bytes")
net_st.net__punch_b = buffer(4)
nb_put8(net_st.net__punch_b, 0, 'M')
nb_put8(net_st.net__punch_b, 1, 'P')
}
for k in 0 .. 16 {
if net_st.net__punch_left[k] <= 0 { continue }
NetSocket.send(net_st.net__sock, net_st.net__punch_ip[k], net_st.net__punch_port[k], net_st.net__punch_b, 4)
net_st.net__punch_left[k] -= 1
}
}
function net__punch_clear(net_st: mut NetState) -> void {
if net_st.net__punch_left != null { for k in 0 .. 16 { net_st.net__punch_left[k] = 0 } }
}