Search code examples
pythonwebsocketpython-asyncioaiohttp

How to display value from asyncio in web browser page using WebSocket


I'm new to asyncio and aiohttp as well as WebSockets. Basically, I need to generate a random string, change it every second and display its value on the web page without refreshing.

I wrote the following code: 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

But it only displays random string value in the console.

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)

I know that I need to use WebSockets for this task but can't understand from the tutorials how to implement and connect all the components. Will be glad if somebody can help me.


Solution

  • Just resolved it on the client side.

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