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://orwss://depending on certificate, optionalperMessageDeflatecompression- Binary messages:
bytes,bytearrayormemoryviewas data, received asbytes - 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.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | |
|---|---|---|---|---|
| xsocket-2.1.0.tar.gz | 13.3 kB | Without provenance | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| xsocket-2.1.0-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 27.7 kB
Release files / xsocket-2.1.0.tar.gz
| Download URL | xsocket-2.1.0.tar.gz |
|---|---|
| Size | 13.3 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
ce9f9c4b08f3748db60f9c85df82d58ccf20a8ac8c7bf089a7cc57b83058d229
|
|
BLAKE2b-256 checksum How to use checksums |
2508f78d507fb22ba02855f4916f25363645b93491a9b50f745eee9792b911c3
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.14.6
|
Release files / xsocket-2.1.0-py3-none-any.whl
| Download URL | xsocket-2.1.0-py3-none-any.whl |
|---|---|
| Size | 14.4 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
a1e9116ef54e9aeaad0a6aa2ce9bf4d1f053410e23e2a80d2f4c89b24cf6c941
|
|
BLAKE2b-256 checksum How to use checksums |
696771cea7978fc24a6e3609c269553815a0dd1f635ac78dd467a19d6b7aae31
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.14.6
|
Security for xsocket 2.1.0
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.
No provenance found
None of the files in this release were uploaded with provenance metadata.
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.