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
Developer-friendly asynchrony for Django

Django Channels Channels augments Django to bring WebSocket, long-poll HTTP, task offloading and other async support to your code, using familiar Djan

Django 5.5k Jan 03, 2023
Websocket 'broadcast' demo using FastAPI/Starlette

fastapi-websocket-broadcast An example of the familiar 'chat' websocket demo app, implemented in FastAPI / Starlette. Run with uvicorn app:app And th

Kit Thwaite 109 Nov 30, 2022
WebSocket and WAMP in Python for Twisted and asyncio

Autobahn|Python WebSocket & WAMP for Python on Twisted and asyncio. Quick Links: Source Code - Documentation - WebSocket Examples - WAMP Examples Comm

Crossbar.io 2.4k Jan 04, 2023
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
tiny multi-threaded socks4 server implemented in python2

tiny, multi-threaded socks4a server implemented in python2.

4 Sep 21, 2022
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
WebSocket client for Python

websocket-client The websocket-client module is a WebSocket client for Python. It provides access to low level APIs for WebSockets. All APIs are for s

3.1k Jan 02, 2023
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
image stream publish server over websocket

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

MrError404 1 Nov 04, 2021
Using python-binance to provide websocket data to freqtrade

The goal of this project is to provide an alternative way to get realtime data from Binance and use it in freqtrade despite the exchange used. It also uses talipp for computing

58 Jan 01, 2023
Async (trio) KuCoin minimal REST API + Websocket

Minimal Async KuCoin REST API + WebSocket using trio Coded by π ([email protected] TG: @p

Pi 2 Oct 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
Get realtime updates in your mobile/web app from frappe and erpnext

Fsocket Extend frappe's websocket server using socket.io and redis Installation Use frappe bench to add fsocket in your project $ bench get-app https:

21 Sep 25, 2022
Chat app for Django, powered by Django Channels, Websockets & Asyncio

Django Private Chat2 New and improved https://github.com/Bearle/django-private-chat Chat app for Django, powered by Django Channels, Websockets & Asyn

Bearle 205 Dec 30, 2022
Elegant WebSockets for your Flask apps.

Flask-Sockets Elegant WebSockets for your Flask apps. Simple usage of route decorator: from flask import Flask from flask_sockets import Sockets app

Heroku Python Team 1.7k Dec 26, 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
Official repository for gevent-socketio

Presentation gevent-socketio is a Python implementation of the Socket.IO protocol, developed originally for Node.js by LearnBoost and then ported to o

Alexandre Bourget 1.2k Dec 12, 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
Python socket.io server implementation on top of Tornado framework

TornadIO2 Disclaimer Unfortunately, Socket.IO 0.8 branch is abandoned, there are huge amount of bugs and nothing getting fixed. I would suggest to loo

Serge S. Koval 526 Oct 03, 2022
JINS MEME(2021年モデル)のJINS MEME LoggerをPythonのWebSocketサーバーで受信するサンプル

JINS-MEME-Python-WebSocketServer-Sample JINS MEME(2021年モデル)のJINS MEME LoggerをPythonのWebSocketサーバーで受信するサンプルです。 Logging Data 以下のデータに対応しています。 各データの定義はJIN

KazuhitoTakahashi 19 Apr 29, 2022