Skip to main content

python-json-socket (jsocket)

CI PyPI Python Versions License

Simple JSON-over-TCP sockets for Python. This library provides:

  • JsonClient/JsonServer: length‑prefixed JSON message framing over TCP
  • ThreadedServer: a single-connection server running in its own thread
  • ServerFactory/ServerFactoryThread: a per‑connection worker model for multiple clients

It aims to be small, predictable, and easy to integrate in tests or small services.

Install

pip install jsocket

Requires Python 3.8+.

Quickstart

Echo server with ThreadedServer and a client:

import time
import jsocket

class Echo(jsocket.ThreadedServer):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.timeout = 2.0  # sets both accept and recv timeouts

    # Return a dict to send a response back to the client
    def _process_message(self, obj):
        if isinstance(obj, dict) and 'echo' in obj:
            return obj
        return None

# Bind to an ephemeral port (port=0)
server = Echo(address='127.0.0.1', port=0)
_, port = server.socket.getsockname()
server.start()

client = jsocket.JsonClient(address='127.0.0.1', port=port)
assert client.connect() is True

payload = {"echo": "hello"}
client.send_obj(payload)
assert client.read_obj() == payload

client.close()
server.stop()
server.join()

Per‑connection workers with ServerFactory:

import jsocket

class Worker(jsocket.ServerFactoryThread):
    def __init__(self):
        super().__init__()
        self.timeout = 2.0  # sets recv timeout for this worker

    def _process_message(self, obj):
        if isinstance(obj, dict) and 'message' in obj:
            return {"reply": f"got: {obj['message']}"}

server = jsocket.ServerFactory(Worker, address='127.0.0.1', port=5489)
server.start()
# Connect one or more clients; one Worker is spawned per connection

API Highlights

  • JsonClient:

    • connect() returns True on success
    • send_obj(dict) sends a JSON object
    • read_obj() blocks until a full message is received; raises socket.timeout or RuntimeError("socket connection broken")
    • timeout sets both accept and recv timeouts
    • accept_timeout controls the server's accept timeout
    • recv_timeout controls the connection read timeout
  • ThreadedServer:

    • Subclass and implement _process_message(self, obj) -> Optional[dict]
    • Return a dict to send a response; return None to send nothing
    • start(), stop(), join() manage the server thread
    • send_obj(dict) sends to the currently connected client
  • ServerFactory / ServerFactoryThread:

    • ServerFactoryThread is a worker that handles one client connection
    • ServerFactory accepts connections and spawns a worker per client

Examples and Tests

  • Examples: see examples/example_servers.py and scripts/smoke_test.py
  • Pytest: end-to-end and listener tests under tests/
    • Run: pytest -q

Behavior-Driven Tests (Behave)

  • Steps live under features/steps/ and environment hooks in features/environment.py.

  • To run Behave scenarios, add one or more .feature files under features/ and run:

    • pip install -r requirements-dev.txt
    • PYTHONPATH=. behave -f progress2
  • A minimal example feature:

    Feature: Echo round-trip
      Scenario: client/server echo
        Given I start the server
        And I connect the client
        When the client sends the object {"echo": "hi"}
        Then the client sees a message {"echo": "hi"}
    

Notes

  • Breaking change: version 2.0.0 uses a new framing header (magic + length + CRC32). v1 clients are incompatible.
  • Message framing uses a 12‑byte header: 4‑byte magic, 4‑byte big‑endian length, and 4‑byte CRC32 of the payload, followed by a JSON payload encoded as UTF‑8.
  • max_message_size defaults to 10MB; set .max_message_size to adjust or set to None to disable.
  • On disconnect, reads raise RuntimeError("socket connection broken") so callers can distinguish cleanly from timeouts.
  • Binding with port=0 lets the OS choose an ephemeral port; find it with server.socket.getsockname().

Links

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

jsocket-2.0.3.tar.gz (38.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

jsocket-2.0.3-py3-none-any.whl (17.3 kB view details)

Uploaded Python 3

File details

Details for the file jsocket-2.0.3.tar.gz.

File metadata

  • Download URL: jsocket-2.0.3.tar.gz
  • Upload date:
  • Size: 38.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.12

File hashes

Hashes for jsocket-2.0.3.tar.gz
Algorithm Hash digest
SHA256 fd2fd78958a1d2e0c02d6bc7a27d36fa2a7b6430e1f9acebf85cf1bd818fff89
MD5 eb435712c72c0df1f128df39a635ee1d
BLAKE2b-256 55e1210a6e543ca371c2681d36097dc21a014b09b61991b9bc27aec6178d96d3

See more details on using hashes here.

File details

Details for the file jsocket-2.0.3-py3-none-any.whl.

File metadata

  • Download URL: jsocket-2.0.3-py3-none-any.whl
  • Upload date:
  • Size: 17.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.12

File hashes

Hashes for jsocket-2.0.3-py3-none-any.whl
Algorithm Hash digest
SHA256 fc652bc0d686f1ffce7e7e2b99625dc38b28d15f4358520a3a56956c69a03c48
MD5 f0e1c30995183c4161edee77eea4bd75
BLAKE2b-256 dfab46d5ca141f114b1c6c44be36ba7ae85bfdbf53d0834d394835424822cecd

See more details on using hashes here.

Release history Release notifications | RSS feed

This release

2.0.3 This release

2 files

2.0.2

1 file

2.0.1

2 files

2.0.0

2 files

1.9.6

2 files

1.9.5

1 file

1.9.3

2 files

1.9.2

2 files

1.9.1

1 file

1.9.0

2 files

1.8.2

2 files

1.8.1

2 files

1.8

2 files

1.7

2 files

1.6.1

2 files

1.6

1 file

1.5

2 files

1.4

2 files

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page