|
| 1 | +import uerrno |
| 2 | +import usocket |
| 3 | +from uasyncio.core import * |
| 4 | + |
| 5 | + |
| 6 | +DEBUG = 0 |
| 7 | +log = None |
| 8 | + |
| 9 | +def set_debug(val): |
| 10 | + global DEBUG, log |
| 11 | + DEBUG = val |
| 12 | + if val: |
| 13 | + import logging |
| 14 | + log = logging.getLogger("uasyncio.udp") |
| 15 | + |
| 16 | + |
| 17 | +class UdpSocket: |
| 18 | + |
| 19 | + def __init__(self, s): |
| 20 | + self.s = s |
| 21 | + |
| 22 | + def recv(self, n): |
| 23 | + try: |
| 24 | + yield IORead(self.s) |
| 25 | + return self.s.recv(n) |
| 26 | + except: |
| 27 | + #print("recv: exc, cleaning up") |
| 28 | + #print(uasyncio.core._event_loop.objmap, uasyncio.core._event_loop.poller) |
| 29 | + #uasyncio.core._event_loop.poller.dump() |
| 30 | + yield IOReadDone(self.s) |
| 31 | + #print(uasyncio.core._event_loop.objmap) |
| 32 | + #uasyncio.core._event_loop.poller.dump() |
| 33 | + raise |
| 34 | + |
| 35 | + def recvfrom(self, n): |
| 36 | + try: |
| 37 | + yield IORead(self.s) |
| 38 | + return self.s.recvfrom(n) |
| 39 | + except: |
| 40 | + #print("recv: exc, cleaning up") |
| 41 | + #print(uasyncio.core._event_loop.objmap, uasyncio.core._event_loop.poller) |
| 42 | + #uasyncio.core._event_loop.poller.dump() |
| 43 | + yield IOReadDone(self.s) |
| 44 | + #print(uasyncio.core._event_loop.objmap) |
| 45 | + #uasyncio.core._event_loop.poller.dump() |
| 46 | + raise |
| 47 | + |
| 48 | + def asendto(self, buf, addr=None): |
| 49 | + while 1: |
| 50 | + res = self.s.sendto(buf, 0, addr) |
| 51 | + #print("send res:", res) |
| 52 | + if res == len(buf): |
| 53 | + return |
| 54 | + print("asento: IOWrite") |
| 55 | + yield IOWrite(self.s) |
| 56 | + |
| 57 | + def aclose(self): |
| 58 | + yield IOReadDone(self.s) |
| 59 | + self.s.close() |
| 60 | + |
| 61 | + |
| 62 | +def udp_socket(host=None, port=None): |
| 63 | + if DEBUG and __debug__: |
| 64 | + log.debug("udp_socket(%s, %s)", host, port) |
| 65 | + s = usocket.socket(usocket.AF_INET, usocket.SOCK_DGRAM) |
| 66 | + s.setblocking(False) |
| 67 | + if host and port: |
| 68 | + ai = usocket.getaddrinfo(host, port) |
| 69 | + addr = ai[0][-1] |
| 70 | + try: |
| 71 | + s.connect(addr) |
| 72 | + except OSError as e: |
| 73 | + if e.args[0] != uerrno.EINPROGRESS: |
| 74 | + raise |
| 75 | + if DEBUG and __debug__: |
| 76 | + log.debug("udp_socket: After connect") |
| 77 | + return UdpSocket(s) |
| 78 | + yield |
0 commit comments