Beispiel #1
0
def start(client, data):
    task1 = tulip.Task(foo(client))
    task2 = tulip.Task(bar(client))

    while True:
        if task1.done() and task2.done():
            client.log(task1.result())
            client.log(task2.result())
            break
        else:
            yield from tulip.sleep(1)
Beispiel #2
0
def run_briefly(loop):
    @tulip.coroutine
    def once():
        pass

    t = tulip.Task(once(), loop=loop)
    loop.run_until_complete(t)
Beispiel #3
0
def print_headers(task):
    response = task.result()
    for k, v in response.items():
        print('{}: {}'.format(k, v[:80]))

    task = tulip.Task(response.read())
    task.add_done_callback(print_body)
Beispiel #4
0
def scanport(port):
    ippat = '10.1.10.%d'
    loop = tulip.get_event_loop()
    loop.add_signal_handler(signal.SIGINT, loop.stop)
    futs = []
    for x in range(1, 255):
        host = ippat % x
        print('trying', host, port, end='\r', flush=True)
        fut = tulip.Task(loop.create_connection(Scanner, host, port),
                          timeout=1)
        futs.append(fut)
        loop.run_until_complete(tulip.sleep(0.001))
    print()
    for fut in futs:
        try:
            loop.run_until_complete(fut)
        except tulip.CancelledError:
            pass
        except os.error as exc:
            if exc.errno == 24:
                print()
                print(exc)
        except Exception as exc:
            print()
            print(exc)
    print()
    loop.call_later(1, loop.stop)
    loop.run_forever()
Beispiel #5
0
    def handle_one_request(self, rline, message):
        self.close()

        # headers
        headers = http.client.HTTPMessage()
        for hdr, val in message.headers:
            headers[hdr] = val

        if 'websocket' in headers.get('UPGRADE', '').lower():
            # init ws
            wsclient = WebSocketProto()
            status, headers = wsclient.serve(
                headers, self.transport, self.rstream)

            write = self.transport.write
            write(b'HTTP/1.1 ' + status.encode())
            for hdr in headers:
                write(hdr)
            write(b'\r\n')

            if status.startswith('101'):
                # start websocket

                @tulip.coroutine
                def rstream():
                    while True:
                        try:
                            data = yield from wsclient.receive()
                            if not data:
                                break
                        except:
                            break

                        data = data.strip()
                        print(data)
                        for wsc in self._connections:
                            if wsc is not wsclient:
                                wsc.send(data.encode())

                print('Someone joined.')
                for wsc in self._connections:
                    wsc.send(b'Someone joined.')

                self._connections.append(wsclient)
                t = tulip.Task(rstream())
                done, pending = yield from tulip.wait([t])
                assert t in done
                assert not pending
                self._connections.remove(wsclient)

                print('Someone disconnected.')
                for wsc in self._connections:
                    wsc.send(b'Someone disconnected.')
        else:
            write = self.transport.write
            write(b'HTTP/1.0 200 Ok\r\n')
            write(b'Content-type: text/html\r\n')
            write(b'\r\n')
            write(WS_SRV_HTML)
Beispiel #6
0
 def switch_protocols():
     ws_proto = websockets.WebSocketCommonProtocol()
     # Disconnect transport from http_proto and connect it to ws_proto
     http_proto.transport = DummyTransport()
     transport._protocol = ws_proto
     ws_proto.connection_made(transport)
     # Run the WebSocket handler in a Tulip Task
     tulip.Task(run_ws_handler(ws_proto))
Beispiel #7
0
def run_briefly(loop):
    @tulip.coroutine
    def once():
        pass

    gen = once()
    t = tulip.Task(gen, loop=loop)
    try:
        loop.run_until_complete(t)
    finally:
        gen.close()
def create_connection_with_cb(on_result, on_error, loop, *args, **kw):
    """ Calls loop.create_connection and runs it to the end.
        On done calls on_result callback
    """
    task = tulip.Task(loop.create_connection(*args, **kw), loop=loop)

    def dispatch_result(task):
        try:
            on_result(*task.result())
        except OSError as exc:
            on_error(exc)

    task.add_done_callback(dispatch_result)
Beispiel #9
0
def main(loop):
    # program which prints evaluation of each expression from stdin
    code = r'''if 1:
                   import os
                   def writeall(fd, buf):
                       while buf:
                           n = os.write(fd, buf)
                           buf = buf[n:]
                   while True:
                       s = os.read(0, 1024)
                       if not s:
                           break
                       s = s.decode('ascii')
                       s = repr(eval(s)) + '\n'
                       s = s.encode('ascii')
                       writeall(1, s)
                   '''

    # commands to send to input
    commands = iter([b"1+1\n", b"2**16\n", b"1/3\n", b"'x'*50", b"1/0\n"])

    # start subprocess and wrap stdin, stdout, stderr
    p = Popen([sys.executable, '-c', code],
              stdin=PIPE,
              stdout=PIPE,
              stderr=PIPE)

    stdin = yield from connect_write_pipe(p.stdin)
    stdout, stdout_transport = yield from connect_read_pipe(p.stdout)
    stderr, stderr_transport = yield from connect_read_pipe(p.stderr)

    # interact with subprocess
    name = {stdout: 'OUT', stderr: 'ERR'}
    registered = {
        tulip.Task(stderr.readline()): stderr,
        tulip.Task(stdout.readline()): stdout
    }
    while registered:
        # write command
        cmd = next(commands, None)
        if cmd is None:
            stdin.close()
        else:
            print('>>>', cmd.decode('ascii').rstrip())
            stdin.write(cmd)

        # get and print lines from stdout, stderr
        timeout = None
        while registered:
            done, pending = yield from tulip.wait(
                registered, timeout=timeout, return_when=tulip.FIRST_COMPLETED)
            if not done:
                break
            for f in done:
                stream = registered.pop(f)
                res = f.result()
                print(name[stream], res.decode('ascii').rstrip())
                if res != b'':
                    registered[tulip.Task(stream.readline())] = stream
            timeout = 0.0

    stdout_transport.close()
    stderr_transport.close()
Beispiel #10
0
def request(method,
            url,
            *,
            params=None,
            data=None,
            headers=None,
            cookies=None,
            files=None,
            auth=None,
            allow_redirects=True,
            max_redirects=10,
            encoding='utf-8',
            version=(1, 1),
            timeout=None,
            compress=None,
            chunked=None,
            session=None,
            loop=None):
    """Constructs and sends a request. Returns response object.

    method: http method
    url: request url
    params: (optional) Dictionary or bytes to be sent in the query string
      of the new request
    data: (optional) Dictionary, bytes, or file-like object to
      send in the body of the request
    headers: (optional) Dictionary of HTTP Headers to send with the request
    cookies: (optional) Dict object to send with the request
    files: (optional) Dictionary of 'name': file-like-objects
       for multipart encoding upload
    auth: (optional) Auth tuple to enable Basic HTTP Auth
    timeout: (optional) Float describing the timeout of the request
    allow_redirects: (optional) Boolean. Set to True if POST/PUT/DELETE
       redirect following is allowed.
    compress: Boolean. Set to True if request has to be compressed
       with deflate encoding.
    chunked: Boolean or Integer. Set to chunk size for chunked
       transfer encoding.
    session: tulip.http.Session instance to support connection pooling and
       session cookies.
    loop: Optional event loop.

    Usage:

      import tulip.http
      >> resp = yield from tulip.http.request('GET', 'http://python.org/')
      >> resp
      <HttpResponse(python.org/) [200]>

      >> data = yield from resp.content.read()

    """
    redirects = 0
    if loop is None:
        loop = tulip.get_event_loop()

    while True:
        req = HttpRequest(method,
                          url,
                          params=params,
                          headers=headers,
                          data=data,
                          cookies=cookies,
                          files=files,
                          auth=auth,
                          encoding=encoding,
                          version=version,
                          compress=compress,
                          chunked=chunked)

        if session is None:
            conn = start(req, loop)
        else:
            conn = session.start(req, loop)

        # connection timeout
        try:
            resp = yield from tulip.Task(conn, timeout=timeout, loop=loop)
        except tulip.CancelledError:
            raise tulip.TimeoutError from None

        # redirects
        if resp.status in (301, 302) and allow_redirects:
            redirects += 1
            if max_redirects and redirects >= max_redirects:
                resp.close()
                break

            r_url = resp.get('location') or resp.get('uri')

            scheme = urllib.parse.urlsplit(r_url)[0]
            if scheme not in ('http', 'https', ''):
                raise ValueError('Can redirect only to http or https')
            elif not scheme:
                r_url = urllib.parse.urljoin(url, r_url)

            url = urllib.parse.urldefrag(r_url)[0]
            if url:
                resp.close()
                continue

        break

    return resp
Beispiel #11
0
def start_client(loop, host, port):
    t = tulip.Task(loop.create_connection(EchoClient, host, port))
    loop.run_until_complete(t)
Beispiel #12
0
def start_client(loop, addr):
    t = tulip.Task(
        loop.create_datagram_endpoint(MyClientUdpEchoProtocol,
                                      remote_addr=addr))
    loop.run_until_complete(t)
Beispiel #13
0
def start_server(loop, addr):
    t = tulip.Task(
        loop.create_datagram_endpoint(MyServerUdpEchoProtocol,
                                      local_addr=addr))
    loop.run_until_complete(t)
Beispiel #14
0
import tulip
from tulip import http


def print_headers(task):
    response = task.result()
    for k, v in response.items():
        print('{}: {}'.format(k, v[:80]))

    task = tulip.Task(response.read())
    task.add_done_callback(print_body)


def print_body(task):
    data = task.result()
    print('\nReceived {} bytes.\n'.format(len(data)))
    tulip.get_event_loop().stop()


if __name__ == '__main__':
    loop = tulip.get_event_loop()

    t = tulip.Task(http.request('GET', 'http://megafeihong.tumblr.com'))
    t.add_done_callback(print_headers)

    loop.run_forever()
Beispiel #15
0

ARGS = argparse.ArgumentParser(
    description="websocket console client for wssrv.py example.")
ARGS.add_argument('--host',
                  action="store",
                  dest='host',
                  default='127.0.0.1',
                  help='Host name')
ARGS.add_argument('--port',
                  action="store",
                  dest='port',
                  default=8080,
                  type=int,
                  help='Port number')

if __name__ == '__main__':
    args = ARGS.parse_args()
    if ':' in args.host:
        args.host, port = args.host.split(':', 1)
        args.port = int(port)

    url = 'http://{}:{}'.format(args.host, args.port)

    loop = tulip.SelectorEventLoop(tulip.selectors.SelectSelector())
    tulip.set_event_loop(loop)

    loop.add_signal_handler(signal.SIGINT, loop.stop)
    tulip.Task(start_client(loop, url))
    loop.run_forever()
Beispiel #16
0
 def connection_made(self, transport):
     self.transport = transport
     self.stream = tulip.StreamBuffer(loop=self._loop)
     self._request_handler = tulip.Task(self.start(), loop=self._loop)