GET/hello_world

WebSockets

To handle real-time communication, Batman learned how to work with WebSockets. He created a WebSocket class and wrapped it around his Robyn app:

Request

GET
/hello_world
from robyn import Robyn, jsonify, WebSocket

app = Robyn(__file__)
websocket = WebSocket(app, "/web_socket")

@websocket.on("message")
def connect():
    return "Hello world, from ws"

@websocket.on("close")
def close():
    return "Goodbye world, from ws"

@websocket.on("connect")
def message():
    return "Connected to ws"


For sending a message to the client, Batman used the sync_send_to method.

Request

GET
/hello_world

  @websocket.on("message")
  def message(ws, msg, global_dependencies) -> str:
      websocket_id = ws.id
      ws.sync_send_to(websocket_id, "This is a message to self")
      return ""

For sending a message to the client in async manner, Batman used the async_send_to method.

Request

GET
/hello_world

  @websocket.on("message")
  async def message(ws, msg, global_dependencies) -> str:
      websocket_id = ws.id
      await ws.async_send_to(websocket_id, "This is a message to self")
      return ""

For sending broadcast messages, Batman used the sync_broadcast method.

Request

GET
/hello_world

  @websocket.on("message")
  def message(ws, msg, global_dependencies) -> str:
      websocket_id = ws.id
      ws.sync_broadcast("This is a message to self")
      return ""

For sending broadcast messages in async style, Batman used the async_broadcast method.

Request

GET
/hello_world

  @websocket.on("message")
  async def message(ws, msg, global_dependencies) -> str:
      websocket_id = ws.id
      await ws.async_broadcast("This is a message to self")
      return ""

What's next?

As the codebase grew, Batman wanted to onboard the justice league to help him manage the application.

Robyn told him about the different ways he could scale his application, and how to use views and subrouters to make his code more readable.