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
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
A websocket client for Source Filmmaker intended to trasmit scene and frame data to other applications.

SFM SOCK A websocket client for Source Filmmaker intended to trasmit scene and frame data to other applications. This software can be used to transmit

KiwifruitDev 2 Jan 08, 2022
Socket.IO integration for Flask applications.

Flask-SocketIO Socket.IO integration for Flask applications. Installation You can install this package as usual with pip: pip install flask-socketio

Miguel Grinberg 4.9k Jan 03, 2023
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
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
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
Websockify is a WebSocket to TCP proxy/bridge. This allows a browser to connect to any application/server/service. Implementations in Python, C, Node.js and Ruby.

websockify: WebSockets support for any application/server websockify was formerly named wsproxy and was part of the noVNC project. At the most basic l

noVNC 3.3k Jan 03, 2023
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
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
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
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
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
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
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
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
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
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