Python asyncore.loop() Examples

The following are 30 code examples of asyncore.loop(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module asyncore , or try the search function .
Example #1
Source File: test_asynchat.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def line_terminator_check(self, term, server_chunk):
        event = threading.Event()
        s = echo_server(event)
        s.chunk_size = server_chunk
        s.start()
        event.wait()
        event.clear()
        time.sleep(0.01)   # Give server time to start accepting.
        c = echo_client(term, s.port)
        c.push(b"hello ")
        c.push(b"world" + term)
        c.push(b"I'm not dead yet!" + term)
        c.push(SERVER_QUIT)
        asyncore.loop(use_poll=self.usepoll, count=300, timeout=.01)
        s.join(timeout=TIMEOUT)
        if s.is_alive():
            self.fail("join() timed out")

        self.assertEqual(c.contents, [b"hello world", b"I'm not dead yet!"])

    # the line terminator tests below check receiving variously-sized
    # chunks back from the server in order to exercise all branches of
    # async_chat.handle_read 
Example #2
Source File: plac_ext.py    From plac with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def interact(self, stdin=sys.stdin, prompt='i> ', verbose=False):
        "Starts an interactive command loop reading commands from the consolle"
        try:
            import readline
            readline_present = True
        except ImportError:
            readline_present = False
        if stdin is sys.stdin and readline_present:  # use readline
            histfile = os.path.expanduser('~/.%s.history' % self.name)
            completions = list(self.commands) + list(self.mpcommands) + \
                list(self.thcommands) + list(self.tm.specialcommands)
            self.stdin = ReadlineInput(completions, histfile=histfile)
        else:
            self.stdin = stdin
        self.prompt = prompt
        self.verbose = verbose
        intro = self.obj.__doc__ or ''
        write(intro + '\n')
        with self:
            self.obj._interact_ = True
            if self.stdin is sys.stdin:  # do not close stdin automatically
                self._manage_input()
            else:
                with self.stdin:  # close stdin automatically
                    self._manage_input() 
Example #3
Source File: test_asynchat.py    From BinderFilter with MIT License 6 votes vote down vote up
def line_terminator_check(self, term, server_chunk):
        event = threading.Event()
        s = echo_server(event)
        s.chunk_size = server_chunk
        s.start()
        event.wait()
        event.clear()
        time.sleep(0.01) # Give server time to start accepting.
        c = echo_client(term, s.port)
        c.push("hello ")
        c.push("world%s" % term)
        c.push("I'm not dead yet!%s" % term)
        c.push(SERVER_QUIT)
        asyncore.loop(use_poll=self.usepoll, count=300, timeout=.01)
        s.join()

        self.assertEqual(c.contents, ["hello world", "I'm not dead yet!"])

    # the line terminator tests below check receiving variously-sized
    # chunks back from the server in order to exercise all branches of
    # async_chat.handle_read 
Example #4
Source File: proxy.py    From fuzzdb-collect with GNU General Public License v3.0 6 votes vote down vote up
def Pinging_Thread(self):
		print "[+] Starting Ping thread"
		wait = True
		while 1:							#loop forever
			if wait: sleep(ping_delay)		#send ping to server interval
			self.mutex_http_req.acquire()	#Ensure that the other thread is not making a request at this time
			try:
				resp_data=HTTPreq(url,"")	#Read response
				if verbose: v_print(pings_n=1)
				if resp_data:					#If response had data write them to socket
					if verbose: v_print(received_d_pt=len(resp_data))
					self.send(resp_data)		#write to socket
					resp_data=""				#clear data
					#not clearing flag in case more data avail.
					wait = False				#Dont wait: if there was data probably there are more
				else:
					wait = True
			finally:
				self.mutex_http_req.release()	
		print "[-] Pinging Thread Exited"
		thread.interrupt_main()		#Signal main thread -> exits 
Example #5
Source File: test_asynchat.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_close_when_done(self):
        s, event = start_echo_server()
        s.start_resend_event = threading.Event()
        c = echo_client('\n', s.port)
        c.push("hello world\nI'm not dead yet!\n")
        c.push(SERVER_QUIT)
        c.close_when_done()
        asyncore.loop(use_poll=self.usepoll, count=300, timeout=.01)

        # Only allow the server to start echoing data back to the client after
        # the client has closed its connection.  This prevents a race condition
        # where the server echoes all of its data before we can check that it
        # got any down below.
        s.start_resend_event.set()
        s.join()

        self.assertEqual(c.contents, [])
        # the server might have been able to send a byte or two back, but this
        # at least checks that it received something and didn't just fail
        # (which could still result in the client not having received anything)
        self.assertTrue(len(s.buffer) > 0) 
Example #6
Source File: test_asynchat.py    From oss-ftp with MIT License 6 votes vote down vote up
def test_close_when_done(self):
        s, event = start_echo_server()
        s.start_resend_event = threading.Event()
        c = echo_client('\n', s.port)
        c.push("hello world\nI'm not dead yet!\n")
        c.push(SERVER_QUIT)
        c.close_when_done()
        asyncore.loop(use_poll=self.usepoll, count=300, timeout=.01)

        # Only allow the server to start echoing data back to the client after
        # the client has closed its connection.  This prevents a race condition
        # where the server echoes all of its data before we can check that it
        # got any down below.
        s.start_resend_event.set()
        s.join()

        self.assertEqual(c.contents, [])
        # the server might have been able to send a byte or two back, but this
        # at least checks that it received something and didn't just fail
        # (which could still result in the client not having received anything)
        self.assertTrue(len(s.buffer) > 0) 
Example #7
Source File: test_asynchat.py    From BinderFilter with MIT License 6 votes vote down vote up
def test_close_when_done(self):
        s, event = start_echo_server()
        s.start_resend_event = threading.Event()
        c = echo_client('\n', s.port)
        c.push("hello world\nI'm not dead yet!\n")
        c.push(SERVER_QUIT)
        c.close_when_done()
        asyncore.loop(use_poll=self.usepoll, count=300, timeout=.01)

        # Only allow the server to start echoing data back to the client after
        # the client has closed its connection.  This prevents a race condition
        # where the server echoes all of its data before we can check that it
        # got any down below.
        s.start_resend_event.set()
        s.join()

        self.assertEqual(c.contents, [])
        # the server might have been able to send a byte or two back, but this
        # at least checks that it received something and didn't just fail
        # (which could still result in the client not having received anything)
        self.assertTrue(len(s.buffer) > 0) 
Example #8
Source File: test_asynchat.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def line_terminator_check(self, term, server_chunk):
        event = threading.Event()
        s = echo_server(event)
        s.chunk_size = server_chunk
        s.start()
        event.wait()
        event.clear()
        time.sleep(0.01) # Give server time to start accepting.
        c = echo_client(term, s.port)
        c.push("hello ")
        c.push("world%s" % term)
        c.push("I'm not dead yet!%s" % term)
        c.push(SERVER_QUIT)
        asyncore.loop(use_poll=self.usepoll, count=300, timeout=.01)
        s.join()

        self.assertEqual(c.contents, ["hello world", "I'm not dead yet!"])

    # the line terminator tests below check receiving variously-sized
    # chunks back from the server in order to exercise all branches of
    # async_chat.handle_read 
Example #9
Source File: test_asyncore.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_quick_connect(self):
        # see: http://bugs.python.org/issue10340
        if self.family in (socket.AF_INET, getattr(socket, "AF_INET6", object())):
            server = BaseServer(self.family, self.addr)
            t = threading.Thread(target=lambda: asyncore.loop(timeout=0.1,
                                                              count=500))
            t.start()
            def cleanup():
                t.join(timeout=TIMEOUT)
                if t.is_alive():
                    self.fail("join() timed out")
            self.addCleanup(cleanup)

            s = socket.socket(self.family, socket.SOCK_STREAM)
            s.settimeout(.2)
            s.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER,
                         struct.pack('ii', 1, 0))
            try:
                s.connect(server.address)
            except OSError:
                pass
            finally:
                s.close() 
Example #10
Source File: ltmain.py    From Python with MIT License 6 votes vote down vote up
def start(type):
  sys.stdout.flush()
  info["type"] = type
  s.send((json.dumps(info)+ "\n").encode('utf-8'));

  sys.stdout = Printer()
  sys.stderr = Printer()

  asyncore.loop() 
Example #11
Source File: test_logging.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def serve_forever(self, poll_interval):
            """
            Run the :mod:`asyncore` loop until normal termination
            conditions arise.
            :param poll_interval: The interval, in seconds, used in the underlying
                                  :func:`select` or :func:`poll` call by
                                  :func:`asyncore.loop`.
            """
            try:
                asyncore.loop(poll_interval, map=self._map)
            except OSError:
                # On FreeBSD 8, closing the server repeatably
                # raises this error. We swallow it if the
                # server has been closed.
                if self.connected or self.accepting:
                    raise 
Example #12
Source File: test_asynchat.py    From oss-ftp with MIT License 6 votes vote down vote up
def line_terminator_check(self, term, server_chunk):
        event = threading.Event()
        s = echo_server(event)
        s.chunk_size = server_chunk
        s.start()
        event.wait()
        event.clear()
        time.sleep(0.01) # Give server time to start accepting.
        c = echo_client(term, s.port)
        c.push("hello ")
        c.push("world%s" % term)
        c.push("I'm not dead yet!%s" % term)
        c.push(SERVER_QUIT)
        asyncore.loop(use_poll=self.usepoll, count=300, timeout=.01)
        s.join()

        self.assertEqual(c.contents, ["hello world", "I'm not dead yet!"])

    # the line terminator tests below check receiving variously-sized
    # chunks back from the server in order to exercise all branches of
    # async_chat.handle_read 
Example #13
Source File: wifi.py    From OpenBCI_Python with MIT License 5 votes vote down vote up
def loop(self):
        asyncore.loop() 
Example #14
Source File: test_ftplib.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def run(self):
        self.active = True
        self.__flag.set()
        while self.active and asyncore.socket_map:
            self.active_lock.acquire()
            asyncore.loop(timeout=0.1, count=1)
            self.active_lock.release()
        asyncore.close_all(ignore_all=True) 
Example #15
Source File: test_asyncore.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def loop_waiting_for_flag(self, instance, timeout=5):
        timeout = float(timeout) / 100
        count = 100
        while asyncore.socket_map and count > 0:
            asyncore.loop(timeout=0.01, count=1, use_poll=self.use_poll)
            if instance.flag:
                return
            count -= 1
            time.sleep(timeout)
        self.fail("flag not set") 
Example #16
Source File: test_ssl.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def run(self):
            self.active = True
            if self.flag:
                self.flag.set()
            while self.active:
                try:
                    asyncore.loop(1)
                except:
                    pass 
Example #17
Source File: test_asyncore.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_dispatcher(self):
        fd = os.open(support.TESTFN, os.O_RDONLY)
        data = []
        class FileDispatcher(asyncore.file_dispatcher):
            def handle_read(self):
                data.append(self.recv(29))
        s = FileDispatcher(fd)
        os.close(fd)
        asyncore.loop(timeout=0.01, use_poll=True, count=2)
        self.assertEqual(b"".join(data), self.d) 
Example #18
Source File: test_ssl.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def ssl_io_loop(self, sock, incoming, outgoing, func, *args, **kwargs):
        # A simple IO loop. Call func(*args) depending on the error we get
        # (WANT_READ or WANT_WRITE) move data between the socket and the BIOs.
        timeout = kwargs.get('timeout', 10)
        count = 0
        while True:
            errno = None
            count += 1
            try:
                ret = func(*args)
            except ssl.SSLError as e:
                # Note that we get a spurious -1/SSL_ERROR_SYSCALL for
                # non-blocking IO. The SSL_shutdown manpage hints at this.
                # It *should* be safe to just ignore SYS_ERROR_SYSCALL because
                # with a Memory BIO there's no syscalls (for IO at least).
                if e.errno not in (ssl.SSL_ERROR_WANT_READ,
                                   ssl.SSL_ERROR_WANT_WRITE,
                                   ssl.SSL_ERROR_SYSCALL):
                    raise
                errno = e.errno
            # Get any data from the outgoing BIO irrespective of any error, and
            # send it to the socket.
            buf = outgoing.read()
            sock.sendall(buf)
            # If there's no error, we're done. For WANT_READ, we need to get
            # data from the socket and put it in the incoming BIO.
            if errno is None:
                break
            elif errno == ssl.SSL_ERROR_WANT_READ:
                buf = sock.recv(32768)
                if buf:
                    incoming.write(buf)
                else:
                    incoming.write_eof()
        if support.verbose:
            sys.stdout.write("Needed %d calls to complete %s().\n"
                             % (count, func.__name__))
        return ret 
Example #19
Source File: test_asyncore.py    From oss-ftp with MIT License 5 votes vote down vote up
def loop_waiting_for_flag(self, instance, timeout=5):
        timeout = float(timeout) / 100
        count = 100
        while asyncore.socket_map and count > 0:
            asyncore.loop(timeout=0.01, count=1, use_poll=self.use_poll)
            if instance.flag:
                return
            count -= 1
            time.sleep(timeout)
        self.fail("flag not set") 
Example #20
Source File: plac_ext.py    From plac with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _make_interpreter(self):
        "The interpreter main loop, from lists of arguments to task objects"
        enter = getattr(self.obj, '__enter__', lambda: None)
        exit = getattr(self.obj, '__exit__', lambda et, ex, tb: None)
        enter()
        task = None
        try:
            for no in itertools.count(1):
                arglist = yield task
                try:
                    cmd, result = self.parser.consume(arglist)
                except SystemExit as e:  # for invalid commands
                    if e.args == (0,):  # raised as sys.exit(0)
                        errlist = []
                    else:
                        errlist = [str(e)]
                    task = SynTask(no, arglist, iter(errlist))
                    continue
                except:  # anything else
                    task = SynTask(no, arglist, gen_exc(*sys.exc_info()))
                    continue
                if not plac_core.iterable(result):  # atomic result
                    task = SynTask(no, arglist, gen_val(result))
                elif cmd in self.obj.mpcommands:
                    task = MPTask(no, arglist, result, self.tm.man)
                elif cmd in self.obj.thcommands:
                    task = ThreadedTask(no, arglist, result)
                else:  # blocking task
                    task = SynTask(no, arglist, result)
        except GeneratorExit:  # regular exit
            exit(None, None, None)
        except:  # exceptional exit
            exit(*sys.exc_info())
            raise 
Example #21
Source File: plac_ext.py    From plac with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __enter__(self):
        "Start the inner interpreter loop"
        self._interpreter = self._make_interpreter()
        self._interpreter.send(None)
        return self 
Example #22
Source File: test_ftplib.py    From oss-ftp with MIT License 5 votes vote down vote up
def run(self):
        self.active = True
        self.__flag.set()
        while self.active and asyncore.socket_map:
            self.active_lock.acquire()
            asyncore.loop(timeout=0.1, count=1)
            self.active_lock.release()
        asyncore.close_all(ignore_all=True) 
Example #23
Source File: plac_ext.py    From plac with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _wrap(self, genobj, stringify_tb=False):
        """
        Wrap the genobj into a generator managing the exceptions,
        populating the .outlist, setting the .status and yielding None.
        stringify_tb must be True if the traceback must be sent to a process.
        """
        self.status = 'RUNNING'
        try:
            for value in genobj:
                if self.status == 'TOBEKILLED':  # exit from the loop
                    raise GeneratorExit
                if value is not None:  # add output
                    self.outlist.append(value)
                    self.notify(decode(value))
                yield
        except Interpreter.Exit:  # wanted exit
            self._regular_exit()
            raise
        except (GeneratorExit, TerminatedProcess, KeyboardInterrupt):
            # soft termination
            self.status = 'KILLED'
        except Exception:  # unexpected exception
            self.etype, self.exc, tb = sys.exc_info()
            self.tb = ''.join(traceback.format_tb(tb)) if stringify_tb else tb
            self.status = 'ABORTED'
        else:
            self._regular_exit() 
Example #24
Source File: brokertcp.py    From scoop with GNU Lesser General Public License v3.0 5 votes vote down vote up
def run(self):
        """Redirects messages until a shutdown message is received.
        """
        asyncore.loop(timeout=0)
        self.shutdown() 
Example #25
Source File: test_asyncore.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_connection_attributes(self):
        server = TCPServer()
        client = BaseClient(server.address)

        # we start disconnected
        self.assertFalse(server.connected)
        self.assertTrue(server.accepting)
        # this can't be taken for granted across all platforms
        #self.assertFalse(client.connected)
        self.assertFalse(client.accepting)

        # execute some loops so that client connects to server
        asyncore.loop(timeout=0.01, use_poll=self.use_poll, count=100)
        self.assertFalse(server.connected)
        self.assertTrue(server.accepting)
        self.assertTrue(client.connected)
        self.assertFalse(client.accepting)

        # disconnect the client
        client.close()
        self.assertFalse(server.connected)
        self.assertTrue(server.accepting)
        self.assertFalse(client.connected)
        self.assertFalse(client.accepting)

        # stop serving
        server.close()
        self.assertFalse(server.connected)
        self.assertFalse(server.accepting) 
Example #26
Source File: test_asynchat.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_empty_line(self):
        # checks that empty lines are handled correctly
        s, event = start_echo_server()
        c = echo_client('\n', s.port)
        c.push("hello world\n\nI'm not dead yet!\n")
        c.push(SERVER_QUIT)
        asyncore.loop(use_poll=self.usepoll, count=300, timeout=.01)
        s.join()

        self.assertEqual(c.contents, ["hello world", "", "I'm not dead yet!"]) 
Example #27
Source File: test_poplib.py    From oss-ftp with MIT License 5 votes vote down vote up
def run(self):
        self.active = True
        self.__flag.set()
        while self.active and asyncore.socket_map:
            self.active_lock.acquire()
            asyncore.loop(timeout=0.1, count=1)
            self.active_lock.release()
        asyncore.close_all(ignore_all=True) 
Example #28
Source File: test_asynchat.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_simple_producer(self):
        s, event = start_echo_server()
        c = echo_client('\n', s.port)
        data = "hello world\nI'm not dead yet!\n"
        p = asynchat.simple_producer(data+SERVER_QUIT, buffer_size=8)
        c.push_with_producer(p)
        asyncore.loop(use_poll=self.usepoll, count=300, timeout=.01)
        s.join()

        self.assertEqual(c.contents, ["hello world", "I'm not dead yet!"]) 
Example #29
Source File: test_asynchat.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_none_terminator(self):
        # Try reading a fixed number of bytes
        s, event = start_echo_server()
        c = echo_client(None, s.port)
        data = "hello world, I'm not dead yet!\n"
        c.push(data)
        c.push(SERVER_QUIT)
        asyncore.loop(use_poll=self.usepoll, count=300, timeout=.01)
        s.join()

        self.assertEqual(c.contents, [])
        self.assertEqual(c.buffer, data) 
Example #30
Source File: test_asynchat.py    From oss-ftp with MIT License 5 votes vote down vote up
def numeric_terminator_check(self, termlen):
        # Try reading a fixed number of bytes
        s, event = start_echo_server()
        c = echo_client(termlen, s.port)
        data = "hello world, I'm not dead yet!\n"
        c.push(data)
        c.push(SERVER_QUIT)
        asyncore.loop(use_poll=self.usepoll, count=300, timeout=.01)
        s.join()

        self.assertEqual(c.contents, [data[:termlen]])