Commit 5053ea86 authored by Kirill Smelkov's avatar Kirill Smelkov Committed by Léo-Paul Géneau

.

parent 7f11d3f6
......@@ -9,23 +9,35 @@ from socket import socket, AF_INET, SOCK_DGRAM, IPPROTO_UDP, SOL_SOCKET, \
SO_REUSEADDR, IPPROTO_IP, IP_ADD_MEMBERSHIP, IP_MULTICAST_TTL, IP_MULTICAST_LOOP, \
inet_aton, INADDR_ANY
from golang import b
from golang import sync, context
group4 = '224.1.1.1'
group6 = 'XXX'
port = 5678
# open_rx returns function to receive from group:port.
def open_rx(group, port):
# mjoin returns socket prepated to send/receive to/from multicast group:port.
def mjoin(group, port, ttl=2):
# XXX autodetect ip4/ip6 based on group addr
sk = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)
sk.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
sk.bind((group, port))
# join group (for rx)
mreq = struct.pack("4sl", inet_aton(group), INADDR_ANY)
sk.setsockopt(IPPROTO_IP, IP_ADD_MEMBERSHIP, mreq)
def _(): # -> data
return sk.recv(4096)
return _
# set ttl and default destination address (for tx)
sk.setsockopt(IPPROTO_IP, IP_MULTICAST_TTL, ttl)
sk.connect((group, port))
# receive what we send
sk.setsockopt(IPPROTO_IP, IP_MULTICAST_LOOP, 1)
return sk
"""
# open_tx returns function to send to group:port.
def open_tx(group, port, ttl=2):
sk = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)
......@@ -34,37 +46,41 @@ def open_tx(group, port, ttl=2):
def _(data):
return sk.sendto(data, (group, port))
return _
"""
def txloop(pkt):
tx = open_tx(group4, port)
def txloop(ctx, sk, pkt):
print("txloop ...")
i = 0
while 1:
if ctx.err():
raise ctx.err()
i += 1
pkt_ = pkt + (b'%d' % i)
print("tx: %r ..." % pkt_)
tx(pkt + (b'%d' % i))
sk.send(pkt + (b'%d' % i))
time.sleep(1)
def rxloop():
rx = open_rx(group4, port)
def rxloop(ctx, sk):
print("rxloop ...")
while 1:
pkt = rx()
if ctx.err():
raise ctx.err()
pkt = sk.recv(4096)
print("rx: %r" % pkt)
def main():
sk = mjoin(group4, port)
action = sys.argv[1]
if action == "tx":
txloop(sys.argv[2])
elif action == "rx":
rxloop()
else:
raise RuntimeError("Unknown action %r" % action)
wg = sync.WorkGroup(context.background())
if "tx" in action:
wg.go(txloop, sk, b(sys.argv[2]))
if "rx" in action:
wg.go(rxloop, sk)
wg.wait()
if __name__ == '__main__':
main()
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment