Skip to main content

Python-Based implementation of SmartFoxServer2X (SFS2X) Protocol.

Project description

from sfs2x.transport import TCPTransport

ZewSFS

ZewSFS is a Python-based implementation of the SmartFoxServer 2X (SFS2X) protocol, offering both client and server-side capabilities. This library provides fundamental data types, transport abstractions (TCP/WebSocket in the future), message encoding/decoding, and extensibility for custom encryption and compression.

Table of Contents


Features

  • Core: Rich, low-level data structures (e.g., SFSObject, SFSArray) mirroring SmartFoxServer object models.
  • Protocol: Easy-to-use encoding/decoding functions to convert between raw bytes and high-level Message objects.
  • Transport: Ready-made TCP server (via TCPAcceptor) and client (TCPTransport) for sending and receiving SFS2X messages.
  • Encryption: Optional AES-128-CBC support via PyCryptodome.

Installation

  1. Clone the Repository

    git clone https://github.com/ZewMSM/ZewSFS.git
    cd ZewSFS
    
  2. Install Dependencies

    pip install -r requirements.txt
    

    Make sure you have Python 3.9+. If you plan to use encrypted packets, install PyCryptodome:

    pip install pycryptodome
    

Quick Start

Note: These examples describe the server-client for the low-Level transport module. High-level server and client modules are currently under development.

Transport Client Example

import asyncio
from sfs2x.transport.factory import client_from_url
from sfs2x.protocol import Message, ControllerID, SysAction
from sfs2x.core import SFSObject


async def run_client():
    async with client_from_url("tcp://localhost:9933") as client:
        payload = SFSObject()
        payload.put_utf_string("message", "Hello from ZewSFS client!")
        
        await client.send(Message(
            controller=ControllerID.SYSTEM,
            action=SysAction.PUBLIC_MESSAGE,
            payload=payload
        ))
    
        response = await client.recv()
        print("Response:", response)


if __name__ == "__main__":
    asyncio.run(run_client())

Server Example

import asyncio
from sfs2x.transport import server_from_url, TCPTransport
from sfs2x.protocol import Message, ControllerID, SysAction
from sfs2x.core import SFSObject


async def handle_client(client: TCPTransport):
    async for message in client.listen():
        response_payload = SFSObject()
        response_payload.put_utf_string("message", "Hello back from server!")
    
        await client.send(Message(
            controller=ControllerID.SYSTEM, 
            action=SysAction.PUBLIC_MESSAGE, 
            payload=response_payload
        ))


async def run_server():
    async for client in server_from_url("tcp://localhost:9933"):
        print(f"New client connected: {client.host}:{client.port}")
        asyncio.create_task(handle_client(client))


if __name__ == "__main__":
    asyncio.run(run_server())

Modules Overview

Core

The core package provides fundamental data structures and serialization logic:

  1. Fields and Arrays:

    • Bool, Byte, Short, Int, Long, Float, Double, UtfString, Text
    • BoolArray, ByteArray, ShortArray, IntArray, LongArray, FloatArray, DoubleArray, UtfStringArray
  2. Containers:

    • SFSObject for key-value pairs
    • SFSArray for sequential lists
  3. Utility Classes:

    • Buffer for reading raw bytes
    • Field as a base for packable items
    • registry, decode, and encode for bridging raw bytes ↔ SFS data types

Protocol

The protocol package focuses on reading/writing SFS2X-compliant packets:

  • Message: High-level class representing a single SFS2X message with controller, action, and payload.
  • Flag: Enum for packet flags (binary, compressed, encrypted, etc.).
  • encode / decode: Convert Message ↔ binary packets, optionally using compression and AES encryption.
  • AESCipher: AES-128-CBC encryption/decryption for securing packets (requires PyCryptodome).

Transport

The transport package provides abstractions for client-server communication:

  • Transport (abstract): Defines the required methods (open, send, recv, close) for any transport.
  • TCPTransport: Client-side implementation using asyncio streams (TCP).
  • TCPAcceptor: Server-side implementation using asyncio start_server (TCP).
  • client_from_url / server_from_url: Factory methods to instantiate a transport from a URL (e.g., tcp://localhost:9933).

Usage Examples

Working with SFSObject and SFSArray

Imperative style:

from sfs2x.core import SFSObject, SFSArray

obj = SFSObject()
obj.put_int("score", 1200)
obj.put_double_array("history", [3.14, -4.5, 2.7]) \
    .put_bool("isAdmin", True)

arr = SFSArray()
arr.add_utf_string("item1")
arr.add_utf_string("item2")

obj["myArray"] = arr

Declarative style:

from sfs2x.core import UtfString, Int, SFSObject, SFSArray

obj = SFSObject({
    "name": UtfString("Zewsic"),
    "score": Int(2022),
    "items": SFSArray([
        UtfString("Sword"),
        UtfString("Shield"),
        SFSObject({"key": UtfString("value")})
    ])
})

Serialization / Deserialization

from sfs2x.core import decode, SFSObject, Int

# Serialize
obj = SFSObject({"example": Int(42)})
raw_bytes = obj.to_bytes()

# Deserialize
deserialized_obj: SFSObject = decode(raw_bytes)
print(deserialized_obj.get("example"))  # 42

Encrypted or Compressed Packets

When creating or decoding messages, you can specify a threshold for compression and a key for encryption:

from sfs2x.protocol import Message, encode, decode, SysAction, ControllerID
from sfs2x.core import SFSObject, UtfString

encryption_key = b"my_secret_16byte"

# Compress if payload > 512 bytes, encrypt with a 16-byte key
msg = Message(controller=ControllerID.EXTENSION, action=18, payload=SFSObject({"secret": UtfString("HideMe")}))
packet = encode(msg, compress_threshold=512, encryption_key=encryption_key)

# Decoding
decoded_msg = decode(packet, encryption_key=encryption_key)

Project details


Download files

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

Source Distribution

sfs2x-0.1.0.tar.gz (20.0 kB view details)

Uploaded Source

Built Distribution

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

sfs2x-0.1.0-py3-none-any.whl (20.5 kB view details)

Uploaded Python 3

File details

Details for the file sfs2x-0.1.0.tar.gz.

File metadata

  • Download URL: sfs2x-0.1.0.tar.gz
  • Upload date:
  • Size: 20.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.7.1

File hashes

Hashes for sfs2x-0.1.0.tar.gz
Algorithm Hash digest
SHA256 cf873bf7dcba251ed8414409a539f923ad41f36c64c26f529cb6589255212db8
MD5 aa74def31f238663070a3bf8b6985728
BLAKE2b-256 c290f8f3f526b4a9a92f83b3a4ccda9160b828a55e71f7a2e90430ccb42e4c94

See more details on using hashes here.

File details

Details for the file sfs2x-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: sfs2x-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 20.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.7.1

File hashes

Hashes for sfs2x-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 6336f004f1d76020900d30522b0916f05257c2361512cd9bcdcea545b2091311
MD5 935f351bcb92a778a68078dbfedb921f
BLAKE2b-256 de890771b823ff874ce75b23f3016d531de1ba71f13f2527513b6eb3260b75e2

See more details on using hashes here.

Supported by

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