Skip to main content

rfr# xSocket for Python

WebSocket client and server for Python (asyncio). Same protocol as xSocket for Node.js and the browser: a Python server works with JS clients, a Python client works with a Node.js server.

  • Request-response with TTL (sendReady), clock synchronization with the server
  • Automatic reconnect and session recovery within socketObjectTimeout
  • Auth hook on the server (use('auth'))
  • ws:// or wss:// depending on certificate, optional perMessageDeflate compression
  • Binary messages: bytes, bytearray or memoryview as data, received as bytes
  • Python 3.9+, depends on websockets
pip install xsocket

The API mirrors the JS version. Methods that return a Promise in JS (send, sendReady, response) return an awaitable task here: the message is sent even without await. Event handlers can be regular functions or coroutines and receive the same arguments as in JS. Client and Server must be created inside a running event loop.

Server:

import asyncio
import xsocket

async def main():
    xServer = xsocket.Server({
        'port' : 8752, # (Not necessary) Port listen (Default: 443 with certificate, 80 without)
        'socketObjectTimeout' : 30000, # (Not necessary) Allows the user to reconnect within 30 seconds (Default: 0)
        'perMessageDeflate' : True, # (Not necessary) Compress messages (Default: False)
        'https' : { # (Not necessary) Without certificate server uses ws:// instead of wss://
            'cert' : '<path>/cert.pem',
            'key' : '<path>/private.key'
        }
    })

    # (Not necessary) Auth, by default all connections are allowed. Can be async
    def auth(xSocketObject, success, failed):
        if xSocketObject.getQueryVal('name'):
            return success()
        failed('Access denied')

    xServer.use('auth', auth)

    def onConnect(xSocketObject):
        print('Connect event:', xSocketObject.getID(), xSocketObject.getIP(), xSocketObject.getOrigin(), xSocketObject.getQuery(), xSocketObject.getReqHeaders())

        async def onData(xSocketData):
            print('Data event', xSocketData.getID(), xSocketData.getType(), xSocketData.getData())
            await asyncio.sleep(1)
            try:
                await xSocketData.response({'welcome' : 'Hello ' + xSocketObject.getQueryVal('name')})
                # OR
                # await xSocketData.response({}, 'Permision denied')
            except xsocket.XSocketError as e:
                print('Response send failed', xSocketData.getID(), e)

        xSocketObject.on('data', onData)
        xSocketObject.on('disconnect', lambda xSocketObject, msg: print('Disconnect event:', xSocketObject.getID(), msg))
        xSocketObject.on('reconnect', lambda xSocketObject: print('Reconnect event:', xSocketObject.getID()))
        xSocketObject.on('destroy', lambda xSocketObject, msg: print('Destroy event:', xSocketObject.getID(), msg))

    xServer.on('connect', onConnect)
    xServer.on('listen', lambda: print('Listen event', xServer.getPort()))

    await xServer.listen()
    await asyncio.Future()

asyncio.run(main())

Client:

import asyncio
import xsocket

async def main():
    xClient = xsocket.Client(['wss://server_domain.com:8752'], {'name' : 'Bob'}) # ws:// if server without certificate
    # Self-signed certificate: xsocket.Client(url, query, {'ssl' : ssl.SSLContext})

    xClient.on('reconnect', lambda xSocketObject: print('reconnect event', xSocketObject.getID()))
    xClient.on('disconnect', lambda xSocketObject, msg: print('disconnect', xSocketObject.getID(), msg))
    xClient.on('destroy', lambda xSocketObject, msg: print('destroy', xSocketObject.getID(), msg))

    # Messages from server
    xClient.on('data', lambda xSocketData: xSocketData.response({'ok' : True}))

    xSocketObject = await xClient.getSocketObjectReady()
    print('connect event:', xSocketObject.getID())

    try:
        xSocketData = await xClient.sendReady(
            'helloServer', # Name message
            {'message' : 'Hello server'}, # Data message
            2000 # TTL ready response (Default: 3s)
        )
        print('Server responsed #' + xSocketData.getID(), xSocketData.getType(), xSocketData.getResData())
    except xsocket.XSocketError as e:
        print('Server responsed error', e)

    # Binary message, response can be binary too
    # xSocketData = await xClient.sendReady('file', b'\x01\x02\x03')

    # Without waiting for response
    # await xClient.send('log', {'message' : 'Hello'}, 0)

    # Close connection and destroy session on server
    await xClient.close()

asyncio.run(main())

Metadata

Release files for xsocket 2.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for xsocket 2.1.1
File Size Uploaded Provenance
xsocket-2.1.1.tar.gz 13.2 kB With provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for xsocket 2.1.1
File Interpreter ABI Platform
xsocket-2.1.1-py3-none-any.whl Python 3 none any Details

Total release size: 27.6 kB

Release files / xsocket-2.1.1.tar.gz

Download URL xsocket-2.1.1.tar.gz
Size 13.2 kB
Tags Source
SHA-256 checksum
How to use checksums
c8aa57fe62cbf6d66db11431a50c1a37547942d67a308590bf3333a95afdae39
BLAKE2b-256 checksum
How to use checksums
86b04abc3a539456d5dd808e459a251cf624886ad6e3044fd1d68f314ee3fe5a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 24, 2026.

Transparency log

Release files / xsocket-2.1.1-py3-none-any.whl

Download URL xsocket-2.1.1-py3-none-any.whl
Size 14.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
f3c9904acfd787d27fd956f74ef5a1280adbded1d75c1abed1d41c907746cb2a
BLAKE2b-256 checksum
How to use checksums
c182a1f9a05c94461270113e1693211925a897611c8b9a666b65aa0ecce378b2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 24, 2026.

Transparency log

Security for xsocket 2.1.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

All 2 files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for xsocket-2.1.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 24, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

2.1.1 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page