コード例 #1
0
async def tick(request):
    if 'text/event-stream' not in request.headers.getall('ACCEPT', []):
        raise HTTPNotAcceptable(
            reason="'text/event-stream' not found in Accept headers.")

    resp = StreamResponse(status=200,
                          reason='OK',
                          headers={
                              'Content-Type': 'text/event-stream',
                              'Cache-Control': 'no-cache',
                              'Connection': 'keep-alive'
                          })

    log.debug('Opening new event stream on request: %s', request)
    await resp.prepare(request)

    request.app.connections.add(resp)
    resp.should_stop = False
    try:
        while not resp.should_stop:
            ts = time.monotonic()
            payload = json.dumps({'data': ts})
            resp.write(build_message(payload, id=ts, event='tick'))
            await resp.drain()
            await asyncio.sleep(1)

    finally:
        request.app.connections.remove(resp)

    return resp
コード例 #2
0
async def tick(request):
    #print('what??')
    if 'text/event-stream' not in request.headers.getall('ACCEPT', []):
        raise HTTPNotAcceptable(
            reason="'text/event-stream' not found in Accept headers.")

    resp = StreamResponse(status=200,
                          reason='OK',
                          headers={
                              'Content-Type': 'text/event-stream',
                              'Cache-Control': 'no-cache',
                              'Connection': 'keep-alive'
                          })

    log.debug('Opening new event stream on request: %s', request)
    await resp.prepare(request)

    request.app.connections.add(resp)
    resp.should_stop = False
    try:
        while not resp.should_stop:
            ts = time.monotonic()
            print('ㅎㅎㅎ')
            #fut = asyncio.open_connection('utylee.dlinkddns.com', 1117, loop=loop)
            '''
            try:
                reader, writer = await asyncio.wait_for(fut, timeout=3)
            except:
                ts = 'exception, maybe Timeout...'
                print(ts)
                return
            '''
            '''
            writer.write('utyleeping'.encode())
            rbuf = await reader.read(100)
            print(f'rbuf:{rbuf}')
            ts = rbuf.decode()
            '''

            payload = json.dumps({'data': ts})
            resp.write(build_message(payload, id=ts, event='tick'))
            await resp.drain()
            await asyncio.sleep(5)

    finally:
        request.app.connections.remove(resp)

    return resp