def test_bind(self): s1 = asyncore.dispatcher() s1.create_socket(socket.AF_INET, socket.SOCK_STREAM) s1.bind((HOST, 0)) s1.listen(5) port = s1.socket.getsockname()[1] s2 = asyncore.dispatcher() s2.create_socket(socket.AF_INET, socket.SOCK_STREAM) # EADDRINUSE indicates the socket was correctly bound self.assertRaises(socket.error, s2.bind, (HOST, port))
def test_bind(self): if HAS_UNIX_SOCKETS and self.family == socket.AF_UNIX: self.skipTest("Not applicable to AF_UNIX sockets.") s1 = asyncore.dispatcher() s1.create_socket(self.family) s1.bind(self.addr) s1.listen(5) port = s1.socket.getsockname()[1] s2 = asyncore.dispatcher() s2.create_socket(self.family) # EADDRINUSE indicates the socket was correctly bound self.assertRaises(OSError, s2.bind, (self.addr[0], port))
def test_unhandled(self): d = asyncore.dispatcher() # capture output of dispatcher.log_info() (to stdout via print) fp = StringIO() stdout = sys.stdout try: sys.stdout = fp d.handle_expt() d.handle_read() d.handle_write() d.handle_connect() d.handle_accept() finally: sys.stdout = stdout lines = fp.getvalue().splitlines() expected = [ "warning: unhandled exception", "warning: unhandled read event", "warning: unhandled write event", "warning: unhandled connect event", "warning: unhandled accept event", ] self.assertEquals(lines, expected)
def add_socket(self, local_address, peer, remote_address, sock=None): if sock != None: key=local_address+"==>"+peer+"==>"+remote_address self.client_socks[key] = asyncore.dispatcher(sock, map=self.map) self.client_socks[key].writable=lambda: False self.client_socks[key].handle_read=lambda: self.handle_read(local_address, peer, remote_address) self.client_socks[key].handle_close=lambda: self.handle_close(key) else: self.server_socks[local_address] = asyncore.dispatcher(map=self.map) self.server_socks[local_address].create_socket(socket.AF_INET, socket.SOCK_STREAM) self.server_socks[local_address].writable=lambda: False self.server_socks[local_address].set_reuse_addr() portaddr_split=local_address.rfind(':') self.server_socks[local_address].bind((local_address[:portaddr_split], int(local_address[portaddr_split+1:]))) self.server_socks[local_address].handle_accept = lambda: self.handle_accept(local_address, peer, remote_address) self.server_socks[local_address].listen(1023)
def run(self): this_map = {} trace_socket_path = self.trace_socket_parent_dir + u'/trace_socket' if os.path.exists(trace_socket_path): os.remove(trace_socket_path) LiveTraceServer(trace_socket_path, sock=socket.socket(socket.AF_UNIX, socket.SOCK_STREAM), map=this_map) a = asyncore.dispatcher(sock=self.pipe[0], map=this_map) def handle_read(): raise asyncore.ExitNow def readable(): return True def writable(): return False a.handle_read = handle_read a.readable = readable a.writable = writable while not self.stopped(): try: asyncore.loop(None, False, this_map) except asyncore.ExitNow: break TRACE('ARGH DYING')
def test_create_socket(self): s = asyncore.dispatcher() s.create_socket(self.family) self.assertEqual(s.socket.type, socket.SOCK_STREAM) self.assertEqual(s.socket.family, self.family) self.assertEqual(s.socket.gettimeout(), 0) self.assertFalse(s.socket.get_inheritable())
def setUp(self): print "ServerTestCase" print "--------------" class ServerChannel(Channel): def Network_hello(self, data): print "*Server* ran test method for 'hello' action" print "*Server* received:", data self._server.received = data class EndPointChannel(Channel): connected = False def Connected(self): print "*EndPoint* Connected()" def Network_connected(self, data): self.connected = True print "*EndPoint* Network_connected(", data, ")" print "*EndPoint* initiating send" self.Send(ServerTestCase.testdata) class TestServer(Server): connected = False received = None def Connected(self, channel, addr): self.connected = True print "*Server* Connected() ", channel, "connected on", addr self.server = TestServer(channelClass=ServerChannel) sender = asyncore.dispatcher(map=self.server._map) sender.create_socket(socket.AF_INET, socket.SOCK_STREAM) sender.connect(("localhost", 31425)) self.outgoing = EndPointChannel(sender, map=self.server._map)
def connect_ack_handler(self, iq): try: key=iq_to_key(iq['connect_ack']) except ValueError: logging.warn('recieved bad port') return() if key in self.client_sockets: logging.debug("key not found in sockets or pending connections") return() for alias in key[1]: key0=(key[0], sleekxmpp.xmlstream.JID(alias).bare, key[2]) if key0 in self.pending_connections: break if key0 in self.pending_connections: logging.debug("%s:%d recieved connection result: " % key[0] + iq['connect_ack']['response'] + " from %s:%d" % key[2]) self.peer_resources[key0[1]]=iq['from'] if iq['connect_ack']['response']=="failure": self.pending_connections[key0].close() del(self.pending_connections[key0]) else: try: peer_maxsize=int(iq['connect_ack']['response']) except ValueError: logging.warn("bad result recieved") return() self.client_sockets[key] = asyncore.dispatcher(self.pending_connections.pop(key0), map=self.map) self.client_sockets[key].peer_maxsize=peer_maxsize self.client_sockets[key].aliases=iq['connect_ack']['aliases'].split(',') self.initialize_client_socket(key) else: logging.warn('iq not in pending connections')
def test_bind(self): s1 = asyncore.dispatcher() s1.create_socket(socket.AF_INET, socket.SOCK_STREAM) s1.bind((HOST, 0)) s1.listen(5) port = s1.socket.getsockname()[1] s2 = asyncore.dispatcher() s2.create_socket(socket.AF_INET, socket.SOCK_STREAM) # On jython, binding is not enough to create a server socket. # Must first bind s2.bind((HOST, port)) # And then listen, which will cause the actual server socket to be created # and then to listen, and thus cause the error # EADDRINUSE indicates the socket was correctly bound self.assertRaises(socket.error, s2.listen, (5))
def test_issue_8594(self): d = asyncore.dispatcher(socket.socket()) # make sure the error message no longer refers to the socket # object but the dispatcher instance instead try: d.foo except AttributeError, err: self.assertTrue('dispatcher instance' in str(err))
def __init__(self, *args, **kwargs): ProxyThread.__init__(self, *args, **kwargs) self._incomingBuffer = b'' self._outgoingBuffer = b'' self._asyncSockets = {} self._asyncIncoming = _asyncore.dispatcher(self.getIncomingSocket(), self._asyncSockets) self._asyncIncoming.handle_read = self._incomingRead self._asyncIncoming.handle_write = self._incomingWrite self._asyncIncoming.writable = self._incomingWritable self._asyncIncoming.handle_close = self._handleClose self._asyncOutgoing = _asyncore.dispatcher(self._mkOutgoingSocket(), self._asyncSockets) self._asyncOutgoing.handle_read = self._outgoingRead self._asyncOutgoing.handle_write = self._outgoingWrite self._asyncOutgoing.writable = self._outgoingWritable self._asyncOutgoing.handle_close = self._handleClose self._readSize = self._getReadSize() self._buffered = self._isBuffered()
def add_server_socket(self, local_address, peer, remote_address): """Create a listener and put it in the server_sockets dictionary.""" self.bot_index=(self.bot_index+1)%len(self.bots) self.server_sockets[local_address] = asyncore.dispatcher(map=self.map) #just some asyncore initialization stuff self.server_sockets[local_address].create_socket(socket.AF_INET, socket.SOCK_STREAM) self.server_sockets[local_address].writable=lambda: False self.server_sockets[local_address].set_reuse_addr() self.server_sockets[local_address].bind(local_address) self.server_sockets[local_address].handle_accept = lambda: self.handle_accept(local_address, peer, remote_address) self.server_sockets[local_address].listen(1023)
def test_create_socket(self): s = asyncore.dispatcher() s.create_socket(self.family) self.assertEqual(s.socket.family, self.family) SOCK_NONBLOCK = getattr(socket, 'SOCK_NONBLOCK', 0) sock_type = socket.SOCK_STREAM | SOCK_NONBLOCK if hasattr(socket, 'SOCK_CLOEXEC'): self.assertIn(s.socket.type, (sock_type | socket.SOCK_CLOEXEC, sock_type)) else: self.assertEqual(s.socket.type, sock_type)
def RestartAsyncore(): """ Informs the asyncore loop of a new socket to handle. """ oldDispatcher = eg.dummyAsyncoreDispatcher dispatcher = asyncore.dispatcher() dispatcher.create_socket(socket.AF_INET, socket.SOCK_STREAM) eg.dummyAsyncoreDispatcher = dispatcher if oldDispatcher: oldDispatcher.close() if oldDispatcher is None: # create a global asyncore loop thread threading.Thread(target=asyncore.loop, name="AsyncoreThread").start()
def test_issue_8594(self): d = asyncore.dispatcher(socket.socket()) # make sure the error message no longer refers to the socket # object but the dispatcher instance instead try: d.foo except AttributeError as err: self.assertTrue('dispatcher instance' in str(err)) else: self.fail("exception not raised") # test cheap inheritance with the underlying socket self.assertEqual(d.family, socket.AF_INET)
def test_log(self): d = asyncore.dispatcher() # capture output of dispatcher.log() (to stderr) l1 = "Lovely spam! Wonderful spam!" l2 = "I don't like spam!" with support.captured_stderr() as stderr: d.log(l1) d.log(l2) lines = stderr.getvalue().splitlines() self.assertEqual(lines, ['log: %s' % l1, 'log: %s' % l2])
def _RegisterSocket(self, s, cb_fct): """ Function to register a socket with a mainloop: Subsequently the given callback function is called whenever there is data to be read on the socket. Returns the socket if succeeded; None if fails. As in _Setup(), the returned socket may differ from the one passed in, in which case the debug server will substitute the socket that is used in its code.""" # Try to load Zope modules: May fail early in run try: import asyncore self.fErr.out("################## Imported asyncore from Zope:") self.fErr.out(asyncore.__file__) except: self.fErr.out("################## Unable to import asyncore in Zope process") return None # Try to use modules to register the socket: This fails if # Zope is in the process of being imported outside of this # call but doesn't yet have all its attribs. try: disp = asyncore.dispatcher(sock=s) def null_fct(): pass def false_fct(): return 0 disp.handle_read = cb_fct disp.handle_error = cb_fct disp.handle_expt = cb_fct disp.handle_write = null_fct disp.handle_connect = null_fct disp.handle_accept = null_fct disp.handle_close = null_fct # Disable select for write disp.writable = false_fct # Set socket to blocking try: # This works in Zope 2.2.2, and seems required there (?) [SRAD] disp.set_blocking(1) except: # This is how it would be done in Zope 2.3.0 but there it breaks # attach/detach/reattach and other things! [SRAD] # disp.socket.setblocking(1) pass self.fErr.out("################## Channel socket registered with Zope") return disp # Failed but keep checking except: self.fErr.out("################## Zope asyncore registration failed") import traceback traceback.print_exc() return None
def add_client_socket(self, peer, remote_address, sock): """Add socket to the bot's routing table.""" # Calculate the client_sockets identifier for this socket, and put in the dict. key = (peer, remote_address) self.client_sockets[key] = asyncore.dispatcher(sock, map=self.map) # just some asyncore initialization stuff self.client_sockets[key].buffer = b"" self.client_sockets[key].writable = lambda: len(self.client_sockets[key].buffer) > 0 self.client_sockets[key].handle_write = lambda: self.handle_write(key) self.client_sockets[key].readable = lambda: False self.client_sockets[key].handle_close = lambda: self.handle_close(key)
def __init__(self, parent, localaddr=("127.0.0.1", 30322), map=None): self._parent = parent asynchat.async_chat.__init__(self, map=map) self._ibuffer = "" self.set_terminator(";\n") # address of Pd connection socket self._remote = "" # set up the server socket to do the accept() from Pd's socket self._serversocket = asyncore.dispatcher(map=map) self._serversocket.handle_accept = self.handle_accept_server self._serversocket.create_socket(socket.AF_INET, socket.SOCK_STREAM) self._serversocket.set_reuse_addr() self._serversocket.bind(localaddr) self._serversocket.listen(1)
def test_log_info(self): d = asyncore.dispatcher() # capture output of dispatcher.log_info() (to stdout via print) l1 = "Have you got anything without spam?" l2 = "Why can't she have egg bacon spam and sausage?" l3 = "THAT'S got spam in it!" with support.captured_stdout() as stdout: d.log_info(l1, 'EGGS') d.log_info(l2) d.log_info(l3, 'SPAM') lines = stdout.getvalue().splitlines() expected = ['EGGS: %s' % l1, 'info: %s' % l2, 'SPAM: %s' % l3] self.assertEqual(lines, expected)
def test_issue_8594(self): # XXX - this test is supposed to be removed in next major Python # version d = asyncore.dispatcher(socket.socket()) # make sure the error message no longer refers to the socket # object but the dispatcher instance instead self.assertRaisesRegex(AttributeError, "dispatcher instance", getattr, d, "foo") # cheap inheritance with the underlying socket is supposed # to still work but a DeprecationWarning is expected with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") family = d.family self.assertEqual(family, socket.AF_INET) self.assertEqual(len(w), 1) self.assertTrue(issubclass(w[0].category, DeprecationWarning))
def test_set_reuse_addr(self): sock = socket.socket() try: sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) except socket.error: unittest.skip("SO_REUSEADDR not supported on this platform") else: # if SO_REUSEADDR succeeded for sock we expect asyncore # to do the same s = asyncore.dispatcher(socket.socket()) self.assertFalse(s.socket.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)) s.create_socket(socket.AF_INET, socket.SOCK_STREAM) s.set_reuse_addr() self.assertTrue(s.socket.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)) finally: sock.close()
def test_unhandled(self): d = asyncore.dispatcher() d.ignore_log_types = () # capture output of dispatcher.log_info() (to stdout via print) with support.captured_stdout() as stdout: d.handle_expt() d.handle_read() d.handle_write() d.handle_connect() lines = stdout.getvalue().splitlines() expected = ['warning: unhandled incoming priority event', 'warning: unhandled read event', 'warning: unhandled write event', 'warning: unhandled connect event'] self.assertEqual(lines, expected)
def test_log(self): d = asyncore.dispatcher() # capture output of dispatcher.log() (to stderr) fp = StringIO() stderr = sys.stderr l1 = "Lovely spam! Wonderful spam!" l2 = "I don't like spam!" try: sys.stderr = fp d.log(l1) d.log(l2) finally: sys.stderr = stderr lines = fp.getvalue().splitlines() self.assertEquals(lines, ["log: %s" % l1, "log: %s" % l2])
def test_unhandled(self): d = asyncore.dispatcher() d.ignore_log_types = () # capture output of dispatcher.log_info() (to stdout via print) with support.captured_stdout() as stdout: d.handle_expt() d.handle_read() d.handle_write() d.handle_connect() lines = stdout.getvalue().splitlines() expected = [ 'warning: unhandled incoming priority event', 'warning: unhandled read event', 'warning: unhandled write event', 'warning: unhandled connect event' ] self.assertEqual(lines, expected)
def test_issue_8594(self): if test_support.due_to_ironpython_bug("http://ironpython.codeplex.com/workitem/28171"): return # XXX - this test is supposed to be removed in next major Python # version d = asyncore.dispatcher(socket.socket()) # make sure the error message no longer refers to the socket # object but the dispatcher instance instead self.assertRaisesRegexp(AttributeError, 'dispatcher instance', getattr, d, 'foo') # cheap inheritance with the underlying socket is supposed # to still work but a DeprecationWarning is expected with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") family = d.family self.assertEqual(family, socket.AF_INET) self.assertTrue(len(w) == 1) self.assertTrue(issubclass(w[0].category, DeprecationWarning))
def handle_transport(self, stanza): """Called when an iq in the https://www.torproject.org/transport/xmpp namespace is received.""" port = int(stanza["tor_initiate"]["port"]) host = stanza["tor_initiate"]["host"] # threading.Thread(target=lambda: self.initiate_connection(stanza['from'], host, port)).start() # construct identifier for client_sockets sid = base64.b32encode(os.urandom(50)) key = "%s %s" % (stanza["from"], sid) self.client_sockets[key] = asyncore.dispatcher(map=self.map) self.client_sockets[key].host = host self.client_sockets[key].port = port stanza.reply() stanza["tor_initiate_success"]["sid"] = sid stanza.send()
def test_set_reuse_addr(self): if HAS_UNIX_SOCKETS and self.family == socket.AF_UNIX: self.skipTest("Not applicable to AF_UNIX sockets.") sock = socket.socket(self.family) try: sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) except OSError: unittest.skip("SO_REUSEADDR not supported on this platform") else: # if SO_REUSEADDR succeeded for sock we expect asyncore # to do the same s = asyncore.dispatcher(socket.socket(self.family)) self.assertFalse(s.socket.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)) s.socket.close() s.create_socket(self.family) s.set_reuse_addr() self.assertTrue(s.socket.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)) finally: sock.close()
def test_set_reuse_addr(self): if HAS_UNIX_SOCKETS and self.family == socket.AF_UNIX: self.skipTest('Not applicable to AF_UNIX sockets.') with socket.socket(self.family) as sock: try: sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) except OSError: unittest.skip('SO_REUSEADDR not supported on this platform') else: s = asyncore.dispatcher(socket.socket(self.family)) self.assertFalse( s.socket.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)) s.socket.close() s.create_socket(self.family) s.set_reuse_addr() self.assertTrue( s.socket.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR))
def initiate_connection(self, local_address, peer, remote_address): """Initiate connection to 'local_address' and add the socket to the client sockets map.""" key=(local_address, peer, remote_address) try: # connect to the ip:port logging.debug("trying to connect to %s:%d" % local_address) connected_socket=socket.create_connection(local_address, timeout=2.0) except (socket.error, OverflowError, ValueError): logging.warning("could not connect to %s:%d" % local_address) #if it could not connect, tell the bot on the the other it could not connect self.send_connect_ack(key, "failure") return() logging.debug("connecting %s:%d" % remote_address + " to %s:%d" % local_address) # attach the socket to the appropriate client_sockets and fix asyncore methods self.client_sockets[key] = asyncore.dispatcher(connected_socket, map=self.map) self.client_sockets[key].aliases=list(key[1]) self.initialize_client_socket(key) self.send_connect_ack(key, str(sys.maxsize))
def test_issue_8594(self): if test_support.due_to_ironpython_bug( "http://ironpython.codeplex.com/workitem/28171"): return # XXX - this test is supposed to be removed in next major Python # version d = asyncore.dispatcher(socket.socket()) # make sure the error message no longer refers to the socket # object but the dispatcher instance instead self.assertRaisesRegexp(AttributeError, 'dispatcher instance', getattr, d, 'foo') # cheap inheritance with the underlying socket is supposed # to still work but a DeprecationWarning is expected with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") family = d.family self.assertEqual(family, socket.AF_INET) self.assertTrue(len(w) == 1) self.assertTrue(issubclass(w[0].category, DeprecationWarning))
def test_set_reuse_addr(self): if HAS_UNIX_SOCKETS and self.family == socket.AF_UNIX: self.skipTest("Not applicable to AF_UNIX sockets.") with socket.socket(self.family) as sock: try: sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) except OSError: unittest.skip("SO_REUSEADDR not supported on this platform") else: # if SO_REUSEADDR succeeded for sock we expect asyncore # to do the same s = asyncore.dispatcher(socket.socket(self.family)) self.assertFalse(s.socket.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)) s.socket.close() s.create_socket(self.family) s.set_reuse_addr() self.assertTrue(s.socket.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR))
def add_server_socket(self, local_address, peer, remote_address, remote_port): """Create a listener and put it in the server_sockets dictionary.""" portaddr_split = local_address.rfind(":") if portaddr_split == -1: raise (Exception("No port specified" + local_address)) self.server_sockets[local_address] = asyncore.dispatcher(map=self.map) # just some asyncore initialization stuff self.server_sockets[local_address].create_socket(socket.AF_INET, socket.SOCK_STREAM) self.server_sockets[local_address].writable = lambda: False self.server_sockets[local_address].set_reuse_addr() self.server_sockets[local_address].bind( (local_address[:portaddr_split], int(local_address[portaddr_split + 1 :])) ) self.server_sockets[local_address].handle_accept = lambda: self.handle_accept( local_address, peer, remote_address, remote_port ) self.server_sockets[local_address].listen(1023)
def test_set_reuse_addr(self): if test_support.due_to_ironpython_bug("http://ironpython.codeplex.com/workitem/28171"): return sock = socket.socket() try: sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) except socket.error: unittest.skip("SO_REUSEADDR not supported on this platform") else: # if SO_REUSEADDR succeeded for sock we expect asyncore # to do the same s = asyncore.dispatcher(socket.socket()) self.assertFalse(s.socket.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)) s.create_socket(socket.AF_INET, socket.SOCK_STREAM) s.set_reuse_addr() self.assertTrue(s.socket.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)) finally: sock.close()
def test_log_info(self): d = asyncore.dispatcher() # capture output of dispatcher.log_info() (to stdout via print) fp = StringIO() stdout = sys.stdout l1 = "Have you got anything without spam?" l2 = "Why can't she have egg bacon spam and sausage?" l3 = "THAT'S got spam in it!" try: sys.stdout = fp d.log_info(l1, 'EGGS') d.log_info(l2) d.log_info(l3, 'SPAM') finally: sys.stdout = stdout lines = fp.getvalue().splitlines() expected = ['EGGS: %s' % l1, 'info: %s' % l2, 'SPAM: %s' % l3] self.assertEqual(lines, expected)
def test_set_reuse_addr(self): if test_support.due_to_ironpython_bug( "http://ironpython.codeplex.com/workitem/28171"): return sock = socket.socket() try: sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) except socket.error: unittest.skip("SO_REUSEADDR not supported on this platform") else: # if SO_REUSEADDR succeeded for sock we expect asyncore # to do the same s = asyncore.dispatcher(socket.socket()) self.assertFalse( s.socket.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)) s.create_socket(socket.AF_INET, socket.SOCK_STREAM) s.set_reuse_addr() self.assertTrue( s.socket.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)) finally: sock.close()
def test_unhandled(self): d = asyncore.dispatcher() d.ignore_log_types = () # capture output of dispatcher.log_info() (to stdout via print) fp = StringIO() stdout = sys.stdout try: sys.stdout = fp d.handle_expt() d.handle_read() d.handle_write() d.handle_connect() finally: sys.stdout = stdout lines = fp.getvalue().splitlines() expected = ['warning: unhandled incoming priority event', 'warning: unhandled read event', 'warning: unhandled write event', 'warning: unhandled connect event'] self.assertEqual(lines, expected)
def initiate_connection(self, local_address, peer, remote_address): """Initiate connection to 'local_address' and add the socket to the client sockets map.""" key = (local_address, peer, remote_address) try: # connect to the ip:port logging.debug("trying to connect to %s:%d" % local_address) connected_socket = socket.create_connection(local_address, timeout=2.0) except (socket.error, OverflowError, ValueError): logging.warning("could not connect to %s:%d" % local_address) #if it could not connect, tell the bot on the the other it could not connect self.send_connect_ack(key, "failure") return () logging.debug("connecting %s:%d" % remote_address + " to %s:%d" % local_address) # attach the socket to the appropriate client_sockets and fix asyncore methods self.client_sockets[key] = asyncore.dispatcher(connected_socket, map=self.map) self.client_sockets[key].aliases = list(key[1]) self.initialize_client_socket(key) self.send_connect_ack(key, str(sys.maxsize))
def connect_ack_handler(self, iq): try: key = iq_to_key(iq['connect_ack']) except ValueError: logging.warn('recieved bad port') return () if key in self.client_sockets: logging.debug("key not found in sockets or pending connections") return () for alias in key[1]: key0 = (key[0], sleekxmpp.xmlstream.JID(alias).bare, key[2]) if key0 in self.pending_connections: break if key0 in self.pending_connections: logging.debug("%s:%d recieved connection result: " % key[0] + iq['connect_ack']['response'] + " from %s:%d" % key[2]) self.peer_resources[key0[1]] = iq['from'] if iq['connect_ack']['response'] == "failure": self.pending_connections[key0].close() del (self.pending_connections[key0]) else: try: peer_maxsize = int(iq['connect_ack']['response']) except ValueError: logging.warn("bad result recieved") return () self.client_sockets[key] = asyncore.dispatcher( self.pending_connections.pop(key0), map=self.map) self.client_sockets[key].peer_maxsize = peer_maxsize self.client_sockets[key].aliases = iq['connect_ack'][ 'aliases'].split(',') self.initialize_client_socket(key) else: logging.warn('iq not in pending connections')
def setUp(self): print("ServerTestCase") print("--------------") class ServerChannel(Channel): def Network_hello(self, data): print("*Server* ran test method for 'hello' action") print("*Server* received:", data) self._server.received = data class EndPointChannel(Channel): connected = False def Connected(self): print("*EndPoint* Connected()") def Network_connected(self, data): self.connected = True print("*EndPoint* Network_connected(", data, ")") print("*EndPoint* initiating send") self.Send(ServerTestCase.testdata) class TestServer(Server): connected = False received = None def Connected(self, channel, addr): self.connected = True print("*Server* Connected() ", channel, "connected on", addr) self.server = TestServer(channelClass=ServerChannel) sender = asyncore.dispatcher(map=self.server._map) sender.create_socket(socket.AF_INET, socket.SOCK_STREAM) sender.connect(("localhost", 31425)) self.outgoing = EndPointChannel(sender, map=self.server._map)
def test_basic(self): d = asyncore.dispatcher() self.assertEqual(d.readable(), True) self.assertEqual(d.writable(), True)
def test_create_socket(self): s = asyncore.dispatcher() s.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.assertEqual(s.socket.family, socket.AF_INET) self.assertEqual(s.socket.type, socket.SOCK_STREAM)
print "*Server* received:", data class EndPointChannel(Channel): def Connected(self): print "*EndPoint* Connected()" def Network_connected(self, data): print "*EndPoint* Network_connected(", data, ")" print "*EndPoint* initiating send" outgoing.Send({"action": "hello", "data": {"a": 321, "b": [2, 3, 4], "c": ["afw", "wafF", "aa", "weEEW", "w234r"], "d": ["x"] * 256}}) def Connected(channel, addr): print "*Server* Connected() ", channel, "connected on", addr server = Server(channelClass=ServerChannel) server.Connected = Connected sender = asyncore.dispatcher() sender.create_socket(socket.AF_INET, socket.SOCK_STREAM) sender.connect(("localhost", 31425)) outgoing = EndPointChannel(sender) from time import sleep print "*** polling for half a second" for x in range(50): server.Pump() outgoing.Pump() sleep(0.001)
def test_create_socket(self): s = asyncore.dispatcher() s.create_socket(self.family) self.assertEqual(s.socket.family, self.family) SOCK_NONBLOCK = getattr(socket, 'SOCK_NONBLOCK', 0) self.assertEqual(s.socket.type, socket.SOCK_STREAM | SOCK_NONBLOCK)
from asyncore import dispatcher from sys import argv from socket import AF_INET,SOCK_STREAM if(len(argv)<2): print("No data") port=argv[1] address=('localhost',port) disp=dispatcher() disp.connect(address) wynik=disp.send("Hello World") if(wynik): print("I go yourm essage") disp.close()
def test_repr(self): d = asyncore.dispatcher() self.assertEqual(repr(d), '<asyncore.dispatcher at %#x>' % id(d))
def __init__(self, address, sock=None): asyncore.dispatcher(self, sock) self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.connect(address)