Browse files

Avoid getpeername() syscall in Socket.connected if possible

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
  • Loading branch information...
1 parent 7d1623b commit e1ea410ef1d4422685ecd2c29df9ab125745a9ad @jtackaberry jtackaberry committed Jan 21, 2012
Showing with 11 additions and 5 deletions.
  1. +11 −5 src/
@@ -225,11 +225,18 @@ def connecting(self):
def connected(self):
Boolean representing the connected state of the socket.
+ When a socket is in the process of connecting, it is considered alive
+ but not connected.
- # Will raise exception if socket is not connected.
- self._channel.getpeername()
- return True
+ if self._connecting:
+ # Another thread is in the process of connecting. Try calling
+ # 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):
# AttributeError is raised if _channel is None, socket.error is
# raised if the socket is disconnected
@@ -534,11 +541,10 @@ def _connect(self, addr, ipv6=True):
self._reqhost = addr[0]
self._resolve_hostname_with_action(addr, sock.connect, ipv6)
+ self.wrap(sock, IO_READ | IO_WRITE)
self._connecting = False
- self.wrap(sock, IO_READ | IO_WRITE)
def connect(self, addr, ipv6=True):

0 comments on commit e1ea410

Please sign in to comment.