Skip to content
Snippets Groups Projects
Commit a4e86484 authored by Piotr Maślanka's avatar Piotr Maślanka
Browse files

Socket connect() status autodetected

Socket constructor does not need to be informed whether socket object
passed is connected or not - it will be autodetected
parent 916454d1
No related branches found
No related tags found
No related merge requests found
......@@ -18,21 +18,31 @@ class Socket(FileDescriptorChannel):
the socket.
"""
def __init__(self, socket, connected=True):
def __init__(self, _socket):
"""@type socket: native network socket or L{Socket}
@param connected: when socket is passed in, connected should express
whether it is already connected"""
Whether socket is connected will be detected automatically by means
of a zero-length write"""
FileDescriptorChannel.__init__(self)
if isinstance(socket, Socket):
self.socket = socket.socket
if isinstance(_socket, Socket):
self.socket = _socket.socket
else:
self.socket = socket
self.socket = _socket
self.active = True
self.blocking = True
self.timeout = None
self.socket.settimeout(None)
self.connected = connected
# Detect whether socket is connected
try:
self.socket.send('')
except socket.error as e:
if e.errno in (10057, 11, 32):
# Resource temporarily unavailable or Broken pipe
self.connected = False
else:
self.connected = True
else:
self.connected = True
def write(self, data):
if not self.active: raise ChannelClosed, 'cannot write - socket closed'
......
......@@ -23,7 +23,7 @@ class SelectHandlingLayerTest(unittest.TestCase):
self.ok = True
mshl = MySelectHandlingLayer(self)
sck = Socket(socket(AF_INET, SOCK_STREAM), connected=False)
sck = Socket(socket(AF_INET, SOCK_STREAM))
mshl.register_channel(sck)
sck.connect(('www.yahoo.com', 80)) # that was just nonblocking
......
......@@ -14,6 +14,29 @@ import unittest
TESTING_PORT = 49998
class SSLSelectHandlingLayerTest(unittest.TestCase):
def test_nonblocking_connect(self):
class MySelectHandlingLayer(SelectHandlingLayer):
def __init__(self, utc):
SelectHandlingLayer.__init__(self)
self.utc = utc
self.ok = False
def on_connected(self, channel):
# at this point data should have been flushed
self.ok = True
mshl = MySelectHandlingLayer(self)
sck = SSLSocket(socket(AF_INET, SOCK_STREAM))
mshl.register_channel(sck)
sck.connect(('www.google.com', 80)) # that was just nonblocking
a = time()
while (time() - a < 30) and (not mshl.ok):
mshl.select()
self.assertEquals(mshl.ok, True)
def test_3_clients(self):
class ConnectorThread(Thread):
def __init__(self, utc):
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment