代码之家  ›  专栏  ›  技术社区  ›  Alex Ermolaev

如何使用WebSocket在web浏览器页面中显示来自asyncio的值

  •  1
  • Alex Ermolaev  · 技术社区  · 7 年前

    我对asyncio和aiohttp以及WebSocket都是新手。基本上,我需要生成一个随机字符串,每秒更改一次,并在网页上显示其值,而无需刷新。

    我编写了以下代码:

    import asyncio
    import random
    import string
    
    from aiohttp import web
    
    
    async def index(request):
        return web.Response(text=periodic())
    
    @asyncio.coroutine
    def periodic():
        while True:
            print(''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10)))
            yield from asyncio.sleep(1)
    
    def stop():
        task.cancel()
    
    task = asyncio.Task(periodic())
    loop = asyncio.get_event_loop()
    
    try:
        loop.run_until_complete(task)
    except asyncio.CancelledError:
        pass
    

    但它只在控制台中显示随机字符串值。

    from aiohttp import web
    from routes import setup_routes
    
    
    app = web.Application()
    setup_routes(app)
    web.run_app(app, host='127.0.0.1', port=8080)
    

    路线。py公司

    from app import index
    
    
    def setup_routes(app):
        app.router.add_get('/', index)
    

    1 回复  |  直到 7 年前
        1
  •  1
  •   Alex Ermolaev    7 年前

    只是在客户端解决了这个问题。

    <!DOCTYPE html>
    <meta charset="utf-8" />
    <html>
    <head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
    </script>
      <script language="javascript" type="text/javascript">
        $(function() {
          var conn = null;
          function log(msg) {
            var control = $('#log');
            control.html('');
            control.html(msg);
            control.scrollTop(control.scrollTop() + 1000);
          }
          function connect() {
            disconnect();
            var wsUri = (window.location.protocol=='https:'&&'wss://'||'ws://')+window.location.host;
            conn = new WebSocket(wsUri);
            log('Connecting...');
            conn.onopen = function() {
              log('Connected.');
              console.log(conn);
            };
            conn.onmessage = function(e) {
              log('Received: ' + e.data);
            };
            conn.onclose = function() {
              log('Disconnected.');
              conn = null;
            };
          }
          function disconnect() {
            if (conn != null) {
              log('Disconnecting...');
              conn.close();
              conn = null;
            }
          }
    
          $('#connect').click(function() {
            if (conn == null) {
              connect();
            } else {
              disconnect();
            }
            return false;
          });
          function repeat(){
              var text = Math.random().toString(36).slice(2);
              log(text);
              conn.send(text);
              setTimeout(repeat, 1000);
          };
          $('#start').click(function() {
            repeat();
            $('#text').val('').focus();
            return false;
          });
          $('#text').keyup(function(e) {
            if (e.keyCode === 13) {
              $('#send').click();
              return false;
            }
          });
        });
    </script>
    </head>
    <body>
    <div>
      <button id="connect">Connect</button>
    </div>
    <div>
      <button id="start">start</button>
    </div>
    <div id="log"
         style="width:20em;height:15em;overflow:auto;border:1px solid black">
    </div>
    </body>
    </html>