Skip to content

Commit

Permalink
Avoid getpeername() syscall in Socket.connected if possible
Browse files Browse the repository at this point in the history
The Socket.connected property will call getpeername() only if _connecting
is True.  Even this is probably not necessary, but at least it avoids the
syscall in he common case (while socket.connected: [...])

Also check the new IOChannel._closing flag.  Socket.connected is False if the
close() was called even if the channel isn't actually closed yet (with
_close())
  • Loading branch information
jtackaberry committed Jan 21, 2012
1 parent 7d1623b commit e1ea410
Showing 1 changed file with 11 additions and 5 deletions.
16 changes: 11 additions & 5 deletions src/sockets.py
Expand Up @@ -225,11 +225,18 @@ def connecting(self):
def connected(self): def connected(self):
""" """
Boolean representing the connected state of the socket. Boolean representing the connected state of the socket.
When a socket is in the process of connecting, it is considered alive
but not connected.
""" """
try: try:
# Will raise exception if socket is not connected. if self._connecting:
self._channel.getpeername() # Another thread is in the process of connecting. Try calling
return True # getpeername() which will raise if not actually connected yet.
self._channel.getpeername()
return True
else:
return self._channel != None and not self._closing
except (AttributeError, socket.error): except (AttributeError, socket.error):
# AttributeError is raised if _channel is None, socket.error is # AttributeError is raised if _channel is None, socket.error is
# raised if the socket is disconnected # raised if the socket is disconnected
Expand Down Expand Up @@ -534,11 +541,10 @@ def _connect(self, addr, ipv6=True):
else: else:
self._reqhost = addr[0] self._reqhost = addr[0]
self._resolve_hostname_with_action(addr, sock.connect, ipv6) self._resolve_hostname_with_action(addr, sock.connect, ipv6)
self.wrap(sock, IO_READ | IO_WRITE)
finally: finally:
self._connecting = False self._connecting = False


self.wrap(sock, IO_READ | IO_WRITE)



def connect(self, addr, ipv6=True): def connect(self, addr, ipv6=True):
""" """
Expand Down

0 comments on commit e1ea410

Please sign in to comment.