async def listen(self, backlog: int): """ Starts listening with the given backlog :param backlog: The socket's backlog :type backlog: int """ if self._fd == -1: raise ResourceClosed("I/O operation on closed socket") self.sock.listen(backlog)
async def bind(self, addr: tuple): """ Binds the socket to an address :param addr: The address, port tuple to bind to :type addr: tuple """ if self._fd == -1: raise ResourceClosed("I/O operation on closed socket") self.sock.bind(addr)
async def close(self): """ Closes the socket asynchronously """ if self._fd == -1: raise ResourceClosed("I/O operation on closed socket") await io_release(self.sock) self.sock.close() self._fd = -1 self.sock = None
async def accept(self): """ Accepts the socket, completing the 3-step TCP handshake asynchronously """ if self._fd == -1: raise ResourceClosed("I/O operation on closed socket") while True: try: remote, addr = self.sock.accept() return type(self)(remote), addr except WantRead: await want_read(self.sock)
async def send_all(self, data: bytes, flags: int = 0): """ Sends all data inside the buffer asynchronously until it is empty """ if self._fd == -1: raise ResourceClosed("I/O operation on closed socket") while data: try: sent_no = self.sock.send(data, flags) except WantRead: await want_read(self.sock) except WantWrite: await want_write(self.sock) data = data[sent_no:]
async def connect(self, address): """ Wrapper socket method """ if self._fd == -1: raise ResourceClosed("I/O operation on closed socket") while True: try: self.sock.connect(address) if self.do_handshake_on_connect: await self.do_handshake() return except WantWrite: await want_write(self.sock)
async def receive(self, max_size: int, flags: int = 0) -> bytes: """ Receives up to max_size bytes from a socket asynchronously """ assert max_size >= 1, "max_size must be >= 1" if self._fd == -1: raise ResourceClosed("I/O operation on closed socket") while True: try: return self.sock.recv(max_size, flags) except WantRead: await want_read(self.sock) except WantWrite: await want_write(self.sock)