Quick start#

Let’s try to write simple http server with WSRPC handler.

import asyncio
import logging
import uuid

import aiohttp.web
from wsrpc_aiohttp import STATIC_DIR, WebSocketAsync


loop = asyncio.get_event_loop()
app = aiohttp.web.Application()
log = logging.getLogger(__name__)


app.router.add_route("*", "/ws/", WebSocketAsync)
app.router.add_static("/js", STATIC_DIR)
app.router.add_static("/", ".")


async def get_random_uuid(_: WebSocketAsync):
    return str(uuid.uuid4())


WebSocketAsync.add_route("uuid4", get_random_uuid)


if __name__ == "__main__":
    logging.basicConfig(level=logging.DEBUG)
    aiohttp.web.run_app(app, port=8000)

Next you have two options:

  1. Browser WSRPC client.

  2. Python WSRPC client.

Browser client#

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <script type="text/javascript" src="/js/wsrpc.js"></script>

  <script type="text/javascript">
    RPC = new WSRPC('/ws/', 5000);
    RPC.connect();
  </script>
  <style>
  body {font-family: "Arial", serif; margin: 10px; background-color: #eee;}
  input {width: 300px;}
  input, button { display: inline-block; border: 1px solid black;}
</style>
</head>
<body>
  <input disabled id="text-field"/>
  <button id="btn">Get UUID</button>
  <script>
    var textField = document.getElementById('text-field');
    var btn = document.getElementById('btn');

    btn.onclick = function () {
      RPC.call('uuid4').then(function (result) {
        textField.value = result;
      }, function (error) {
        alert("Error when call 'uuid4' from remote side: " + error);
      });
    }
  </script>
</body>
</html>

You can try it on http://localhost:8000/web-client.html (required running server.py).

_images/web-client-demo.gif

Python client#

import asyncio

from wsrpc_aiohttp import WSRPCClient


async def main():
    client = WSRPCClient("ws://127.0.0.1:8000/ws/")

    await client.connect()
    print(await client.proxy.uuid4())
    await client.close()


if __name__ == "__main__":
    asyncio.run(main())

This is so useful for testing and shell scripts for your services.

How it works#

The following sequence diagram probably to explain some high level of the data-flow.

_images/explanation.svg