WebSocket implementation in Python built on top of websockets python library. Similar to Node.js's ws.

Related tags

WebSocketws
Overview

ws

WebSocket implementation in Python built on top of websockets python library. Similar to Node.js's ws.

Basic usage.

server.py

import ws

server = ws.ServerSocket()

@server.on('ready')
async def on_ready():
    print(f"Server is ready listening at ws://{server.address}:{server.port}")

@server.on('connect')
async def on_connect(client, path):
    print(f"Client at {client.remote_address} connected.")
    await client.send(
            data={'status':"Okay", "alive": True, "ping": 10.4}
        )

@server.on('message')
async def on_message(message):
    print(f"{message.data}")
    print(f"Received from: {message.author.remote_address} at {message.created_at}")

@server.on('disconnect')
async def on_disconnect(client, code, reason):
    print(f"Client at {client.remote_address} disconnected with code: ", code, "and reason: ", reason)
    print(server.disconnected_clients)

@server.on("close")
async def on_close(client, code, reason):
    print(f"Client at {client.remote_address} closed connection with code: {code} and reason: {reason}")

server.listen("localhost", 3000)

client.py

import ws

client = ws.ClientSocket()

@client.on('connect')
async def on_connect():
    print(f"Connected to {client.connection.remote_address}")
    print(client.connection)

@client.on('message')
async def on_message(message):
    print(f'{message.data}')
    print(f'Status: {message.data.status} Alive: {message.data.alive} Ping: {message.data.ping}')
    print(f"Received from: {message.author.remote_address} at {message.created_at}")
    await message.author.send(content="Okay received.")

@client.on('disconnect')
async def on_disconnect(code, reason):
    print(f"{client.connection} disconnect with code: ", code, "and reason: ", reason)
    print(client.disconnection)

@client.on("close")
async def on_close(code, reason):
    print(f"{client.connection.remote_address} closed connection with code: {code} and reason: {reason}")

client.connect("ws://localhost:3000")

Event collector (.wait_for method) example.

server.py

import ws
import asyncio

server = ws.ServerSocket()

@server.on('ready')
async def on_ready():
    print(f"Server is ready listening at ws://{server.address}:{server.port}")

@server.on('connect')
async def on_connect(websocket, path):
    print(f"Client at {websocket.remote_address} connected.")

@server.on('message')
async def on_message(message):
    print(f"{message.data}")
    if message.data.startswith("!confirm"):
        await message.author.send("Send yes or no?")
        try:
            conmes = await server.wait_for(
                'message', 
                timeout=300, 
                check=lambda rm: rm.data.lower().strip() in ['yes', 'no'] and rm.author.remote_address == message.author.remote_address)
            print(conmes.data)
            if conmes.data.lower().strip() == 'yes':
                await conmes.author.send("done")
            else:
                await conmes.author.send("not done")
        except asyncio.TimeoutError:
            await message.author.send("Timed out!")

@server.on('disconnect')
async def on_disconnect(client, code, reason):
    print(f"{client} disconnect with code:", code, reason)
    print(server.disconnected_clients)

@server.on("close")
async def on_close(client, code, reason):
    print(f"{client.remote_address} closed connection with code: {code} and reason: {reason}")

server.listen("localhost", 3000)

client.py

import ws
import asyncio

client = ws.ClientSocket()

@client.on('connect')
async def on_connect():
    print(f"Connected to {client.connection.remote_address}")
    await client.send(content="!confirm")

@client.on('message')
async def on_message(message):
    print(f'{message.data}')
    if message.data in ['done', 'not done']:
        return
    await asyncio.sleep(3)
    await message.author.send(
         "This is a random message. This won't be collected by the event collector on the server side due to the check condition."
    )
    await asyncio.sleep(3)
    await message.author.send(
        "yes"
    ) #this will be collected and you would receive a response "done" for this, provide "no" and you will get "not done" response

@client.on('disconnect')
async def on_disconnect(code, reason):
    print(f"{client.connection} disconnect with code:", code, reason)
    print(client.disconnection)

@client.on("close")
async def on_close(code, reason):
    print(f"{client.connection.remote_address} closed connection with code: {code} and reason: {reason}")

client.connect("ws://localhost:3000")

FAQ

What's the difference between on_disconnect and on_close event listeners ?

The difference isn't huge but it is there. on_disconnect event is fired only if the client or the server did not closed the connection properly, the TCP Connection was lost suddenly raising the websockets' ConnectionClosedError in the libraries internal message consumer. In such cases the code returned is usually 1006 and there is no reason. While on_close event listener is called if the connection was closed properly, that could be done by calling the libraries' ClientSocket or ServerSocket's .close method and providing a reason and error code optionally. This causes the internal message consumer task on both sides to exit / return that in turn calls the attached listener functions. Note: Unlike on_disconnect listener, on_close is called on both sides that is both on the client and server websocket sides with the same reason and code.

Why this exists?

I made this library because I was fed up of websockets library because it didn't have event based communication like Node.js's ws library and that made it difficult to work about it. Before I was doubtful whether I would work on it anymore or not... but it has went on to become a pretty large library but still not well known as of now...

Owner
AceExpert
AceExpert
An IPC based on Websockets, fast, stable, and reliable

winerp An IPC based on Websockets. Fast, Stable, and easy-to-use, for inter-communication between your processes or discord.py bots. Key Features Fast

Black Thunder 5 Aug 09, 2022
Python Socket.IO server and client

python-socketio Python implementation of the Socket.IO realtime client and server. Version compatibility The Socket.IO protocol has been through a num

Miguel Grinberg 3.2k Dec 31, 2022
Connects microservices through a mesh of websockets

WebMesh WebMesh is a WebSocket based communication library for microservices. It uses a WebSocket server based on wsproto that distributes clients on

Charles Smith 9 Apr 29, 2022
Websocket RPC and Pub/Sub for Python applications and microservices

wampy [whomp-ee] For a background as to what WAMP is, please see here. This is a Python implementation of WAMP using Gevent, but you can also configur

simon 121 Nov 22, 2022
Django Channels HTTP/WebSocket server

daphne Daphne is a HTTP, HTTP2 and WebSocket protocol server for ASGI and ASGI-HTTP, developed to power Django Channels. It supports automatic negotia

Django 1.9k Dec 31, 2022
Whatsapp Clone using django, django-channels and websocket

whatsapp-clone Whatsapp Clone using django, django-channels and websocket Features : Signup/Login One on One personal chat with other user Some screen

Anshu Pal 14 Dec 25, 2022
image stream publish server over websocket

Image Stream Push Server 简介 通过浏览器网页实时查看图像处理结果。 环境 运行程序需要安装一下python依赖: tornado: 用于创建http及websocket服务; opencv-contrib-python: 用于图像数据源获取及图像处理。 使用 进入到src目

MrError404 1 Nov 04, 2021
Library for building WebSocket servers and clients in Python

What is websockets? websockets is a library for building WebSocket servers and clients in Python with a focus on correctness and simplicity. Built on

Aymeric Augustin 4.3k Jan 04, 2023
Python framework for AsyncAPI-documented Websocket, PubSub, and other async constructs

asyncapi-eventrouter Work in Progress Write Python code for Event-Driven Architectures! The asyncapi-eventrouter prototype library creates Websocket,

noteable 4 Jan 27, 2022
Benchmark a WebSocket server's message throughput ⌛

📻 WebSocket Benchmarker ⌚ Message throughput is how fast a WebSocket server can parse and respond to a message. Some people consider this to be a goo

Andrew Healey 24 Nov 17, 2022
Synci - Learning project to create a websocket based client server messaging application

Synci Learning project to create a websocket based client server messaging appli

2 Jan 13, 2022
wssh ("wish") is a command-line utility/shell for WebSocket inpsired by netcat.

wssh ("wish") is a command-line utility/shell for WebSocket inspired by netcat

Jeff Lindsay 256 Nov 16, 2022
Minecraft WebSocket

Minecraft-WebSocket Pythonでマインクラフトと通信します。 紹介動画 推奨設定 Minecraft Windows Edition (Education Edition) 1.17 以上 Python 3系(3.8.2で動作確認済み) 必要なモジュール ・asyncio ・w

Roii.py 2 Jul 07, 2022
alien.py - Python interface to websocket endpoint of ALICE Grid Services

alien.py - Python interface to websocket endpoint of ALICE Grid Services Quick containerized testing: singularity

Adrian Sevcenco 6 Dec 14, 2022
This websocket program is for data transmission between server and client. Data transmission is for Federated Learning in Edge computing environment.

websocket-for-data-transmission This websocket program is for data transmission between server and client. Data transmission is for Federated Learning

9 Jul 19, 2022
A simple texts communication platform using pygame and sockets.

Python Tchat A simple texts communication platform using pygame and sockets. How to install ? You need a python 3.8.6 server with at least one opened

Yohann Boniface 7 Jan 23, 2022
Terminals served by tornado websockets

This is a Tornado websocket backend for the Xterm.js Javascript terminal emulator library. It evolved out of pyxterm, which was part of GraphTerm (as

Project Jupyter 332 Dec 27, 2022
Burgeramt-appointments-websockets - Fetch Bürgeramt appointments and broadcast them via websockets

Bürgeramt appointment finder This server looks for Bürgeramt appointment every f

74 Dec 19, 2022
Library for easily creating and managing websockets.

Documentation coming in version 0.1.4 GitHub PyPI Discord Features Easy to use with object oriented syntax. Intellisense support with typehints and do

ZeroIntensity 0 Aug 27, 2022
Discord.py Connect to Discord voice call with websocket

Discord.py Connect to Discord voice call with websocket

WoahThatsHot 3 Apr 22, 2022