Git Product home page Git Product logo

websocket-rooms's Introduction

ci workflow PyPI Version GitHub

Websocket Rooms: websocket_rooms

A python library for managing and creating WebSocket rooms, for message sharing or data distribution between multiple connections.

Installation

Use pip install websocket-rooms to install this package.

About

This library was created after building several real-time web apps and implementing the same mechanism to broadcast real-time messages between clients listening for the same real-time telemetries. The library simplifies the solution for this issue and proposes a simpler way to handle multiple WebSocket clients that act the same way.

Basic usage example:

Let's create a chatroom where everyone can post their messages:

from websocket_rooms import Room

chat_room = Room()

@chat_room.on_receive("json")
async def on_receive(room: Room, websocket: WebSocket, message: Any) -> None:
    await room.push_json(message)

@chat_room.on_connection
async def on_chatroom_connection(room: Room, websocket: WebSocket) -> None:
    logging.info("{} joined the chat room".format(websocket.client.host))

@chat_app.websocket("/chat")
async def connect_websocket(websocket: WebSocket):
    await chat_room.connect(websocket)

Advanced use case example

Example of a more advanced use case, with modification to the Room base class: Suppose a class RoomWithClientId, where each WebSocket has a client_id associated with it, which it receives on connection:

class RoomWithClientId(Room):
    def __init__(self) -> None:
        super().__init__()
        self._id_to_ws = {}

    async def connect(self, websocket: WebSocket, client_id: int) -> None:
        self._id_to_ws[websocket] = client_id
        await super().connect(websocket)

    def get_client_id(self, websocket: WebSocket) -> int:
        return self._id_to_ws.get(websocket)


chat_room = RoomWithClientId()

@chat_room.on_receive("text")
async def on_chatroom_receive(room: RoomWithClientId, websocket: WebSocket, message: Any) -> None:
    await room.push_json(f"{room.get_client_id(websocket)}: '{message}'")

@chat_room.on_connect("before")
async def before_chatroom_connection(room: RoomWithClientId, websocket: WebSocket) -> None:
    await room.push_json(f"{room.get_client_id(websocket)} is about to join the room!")

@chat_room.on_connect("after")
async def after_chatroom_connection(room: RoomWithClientId, websocket: WebSocket) -> None:
    await room.push_json(f"{room.get_client_id(websocket)} has joined the chat room!")

websocket-rooms's People

Contributors

yoelbassin avatar

Stargazers

Vladislav Sorokin avatar Nikolaus Schlemm avatar Amitai Farber avatar  avatar  avatar Assaf David Hillel avatar  avatar

Watchers

 avatar

websocket-rooms's Issues

Make the `push` function "ordered"

Currently, when pushing a message as a broadcast to the room clients, if multiple messages are sent at the same time, they might be received in a different order by different clients.
This is because we can call await room.push multiple times, and each time async will add the call to its scheduler.
A solution to this problem is when calling room.push(message), the message object will be inserted into an asyncio.queue, while there is one broadcaster task that reads messages from the queue, one at a time, and broadcasts it to all the clients.
Another solution is instead of using a queue, we can create a function with yield statement, to which messages are sent. And sot on every iteration of the broadcaster task, it will receive the next value from this function.
Both solutions require some single broadcaster task that runs constantly.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.