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

时间:2017-09-14 18:59:05

标签: python websocket python-asyncio aiohttp

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

我写了以下代码: 的 app.py

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

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

main.py

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)

routes.py

from app import index


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

我知道我需要使用WebSockets完成此任务,但无法从教程中了解如何实现和连接所有组件。如果有人可以帮助我,我会很高兴的。

1 个答案:

答案 0 :(得分:0)

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

<!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>