1# Copyright (c) 2023, Bjarki Arge Andreasen
2# SPDX-License-Identifier: Apache-2.0
3
4import socket
5import threading
6import select
7
8class TEUDPEcho():
9    def __init__(self):
10        self.running = True
11        self.thread = threading.Thread(target=self._target_)
12
13    def start(self):
14        self.thread.start()
15
16    def stop(self):
17        self.running = False
18        self.thread.join(1)
19
20    def _target_(self):
21        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
22        sock.setblocking(False)
23        sock.bind(('0.0.0.0', 7780))
24
25        while self.running:
26            try:
27                ready_to_read, _, _ = select.select([sock], [sock], [], 0.5)
28
29                if not ready_to_read:
30                    continue
31
32                data, address = sock.recvfrom(4096)
33                print(f'udp echo {len(data)} bytes to  {address[0]}:{address[1]}')
34                sock.sendto(data, address)
35
36            except Exception as e:
37                print(e)
38                break
39
40        sock.close()
41