微算力 · API 导航与自营网关
API 接入 EN
未登录登录
🔌

跨语言实时通信与文件传输专家

Pywayne Cross Comm · v0.1.0
效率 安全 B 级 作者 wangyendt 公开目录收录
1.1k 下载 0 安装 3.8k 收藏 11 浏览

简介

基于 WebSocket 的跨语言实时通信服务,支持多设备消息、文件传输和客户端管理,需配置阿里云 OSS。

原始描述

WebSocket-based cross-language communication service with support for multiple message types (text, JSON, dict, bytes, images, files, folders) and client man...

通过你的 Agent 添加

安装目录:pywayne-cross-comm/(目录名取自 SKILL.md 的 frontmatter name,不是 URL 里的 slug)。

点「快速安装」复制一段指令贴给你的 Agent:它会先下载到 /tmp、把文件清单和校验值给你看,你确认之后才解压安装。不会一步装完、也不改系统其它位置。

或者手动安装

Claude Code~/.claude/skills/pywayne-cross-comm/
Codex CLI~/.codex/skills/pywayne-cross-comm/
DeepSeek Harness~/.agents/skills/pywayne-cross-comm/

包是「根级 SKILL.md + 作者附带的文件」,解压到上面的 <slug>/ 目录即可; 目录名不用换,也不要把包直接解压到 skills 根目录。 技能申请的权限由作者决定:装之前先看清单里有没有脚本、它会读写什么。

中文使用说明 来自收录源

核心用法

pywayne.cross_comm.CrossCommService 提供基于 WebSocket 的实时通信能力,支持 Python 与其他语言的双向通信。使用时需明确指定 role='server' 或 role='client' 初始化实例,服务端通过 start_server() 启动监听,客户端通过 login() 连接并加入网络。消息支持文本、JSON、字典、二进制、图片、文件、文件夹等多种类型,其中文件类传输依赖阿里云 OSS 自动上传下载。

服务端关键特性

  • 通过 @server.message_listener(msg_type=...) 注册异步消息处理器
  • 内置心跳机制(默认 30 秒间隔,60 秒超时)自动管理客户端在线状态
  • get_online_clients() 获取实时在线客户端列表
  • 状态持久化存储于 cross_comm_clients.yaml

客户端关键特性

  • send_message() 支持广播(to_client_id 省略)或定向发送
  • 文件/图片/文件夹类型自动触发 OSS 上传,返回 oss_key
  • list_clients() 可查询全量或仅在线客户端
  • 通过 download_directory 参数控制是否自动下载,避免不必要的带宽消耗
  • download_file_manually() 支持按需手动拉取文件

重要配置

文件传输功能强制依赖环境变量:OSS_ENDPOINT、OSS_BUCKET_NAME、OSS_ACCESS_KEY_ID、OSS_ACCESS_KEY_SECRET,缺失将导致文件类消息发送失败。

显著优点

  1. 协议简洁统一:基于 WebSocket 单连接多路复用,比 HTTP 轮询显著降低延迟
  2. 多语言兼容:任何支持 WebSocket 的语言均可接入,不限于 Python
  3. 消息类型丰富:原生支持结构化数据(dict/JSON)和二进制流传输
  4. 智能文件处理:大文件走 OSS 而非 WebSocket 载荷,避免阻塞消息通道
  5. 灵活下载策略:按消息类型、发送方、目录精细控制自动下载行为

潜在缺点与局限性

  • 外部依赖强:文件传输能力完全绑定阿里云 OSS,无法切换至其他云存储或本地存储
  • 无内置加密:文档未提及 TLS/WSS 支持,生产环境需额外配置反向代理
  • 服务端单点:无集群或多节点负载均衡方案,高可用需自行实现
  • 状态文件局限:客户端状态基于本地 YAML 文件,不适合分布式部署场景
  • MAC 地址暴露:默认 client_id 生成规则包含 MAC 地址,可能存在隐私风险

适合人群

  • 需要快速搭建 Python 与前端/Java/C++ 等语言实时通信通道的开发者
  • 构建 IoT 设备管理、多终端同步、实时通知系统的工程师
  • 已有阿里云 OSS 基础设施,希望低成本集成文件传输的中小团队

常规风险

  • AK 泄露风险:OSS 密钥通过环境变量配置,若部署不当易暴露
  • 无鉴权机制:文档未展示登录认证流程,任意客户端可接入
  • 文件存储不可控:自动上传 OSS 可能产生意外费用,需配置生命周期策略
  • 并发规模未知:未标注 tested 并发连接数,大规模场景需压测验证
  • 网络分区容错:心跳超时判定离线后,消息可能丢失,无明确重试或持久化保证

技能正文


name: pywayne-cross-comm description: WebSocket-based cross-language communication service with support for multiple message types (text, JSON, dict, bytes, images, files, folders) and client management. Use when building real-time communication applications between Python and other languages, needing multi-device messaging, or requiring file transfer via Aliyun OSS. Supports both server and client roles with heartbeat, client list management, and message filtering by type or sender.

Pywayne Cross Comm

pywayne.cross_comm.CrossCommService provides WebSocket-based real-time communication between Python and other languages, with built-in file transfer via Aliyun OSS.

Prerequisites

OSS Configuration (required for file/image/folder transfer):

File transfers use Aliyun OSS. Set these environment variables:

# .env file
OSS_ENDPOINT=your-oss-endpoint
OSS_BUCKET_NAME=your-bucket-name
OSS_ACCESS_KEY_ID=your-access-key
OSS_ACCESS_KEY_SECRET=your-access-secret

For more OSS details, see pywayne-aliyun-oss skill.

Quick Start

import asyncio
from pywayne.cross_comm import CrossCommService, CommMsgType

# Server
server = CrossCommService(role='server', ip='0.0.0.0', port=9898)
await server.start_server()

# Client
client = CrossCommService(role='client', ip='localhost', port=9898, client_id='my_client')
await client.login()

Server

Initialize server

server = CrossCommService(
    role='server',
    ip='0.0.0.0',        # Listen on all interfaces
    port=9898,
    heartbeat_interval=30,     # Seconds between heartbeats
    heartbeat_timeout=60       # Seconds before marking offline
)

Register message listeners

@server.message_listener(msg_type=CommMsgType.TEXT)
async def handle_text(message):
    print(f"From {message.from_client_id}: {message.content}")

@server.message_listener(msg_type=CommMsgType.FILE, download_directory="./downloads")
async def handle_file(message):
    print(f"File downloaded: {message.content}")

Start server

await server.start_server()  # Blocks until server stops

Get online clients

online_clients = server.get_online_clients()  # Returns list of client IDs

Client

Initialize client

client = CrossCommService(
    role='client',
    ip='localhost',           # Server address
    port=9898,
    client_id='my_client',    # Optional: auto-generated if omitted
    heartbeat_interval=30,
    heartbeat_timeout=60
)

Login and logout

success = await client.login()
if success:
    print("Connected!")
    # ... communicate ...
    await client.logout()

Send messages

# Broadcast to all
await client.send_message("Hello!", CommMsgType.TEXT)

# Send to specific client
await client.send_message("Private", CommMsgType.TEXT, to_client_id='target_id')

# JSON message
await client.send_message('{"key": "value"}', CommMsgType.JSON)

# Dict message
await client.send_message({"type": "data", "value": 123}, CommMsgType.DICT)

# Bytes (auto base64 encoded)
await client.send_message(b"binary", CommMsgType.BYTES)

# File (auto uploads to OSS)
await client.send_message("/path/to/file.txt", CommMsgType.FILE)

# Image (auto uploads to OSS)
await client.send_message("/path/to/image.jpg", CommMsgType.IMAGE)

# Folder (auto uploads to OSS)
await client.send_message("/path/to/folder", CommMsgType.FOLDER)

Get client list

# All clients (online + offline)
all_clients = await client.list_clients(only_show_online=False)
# Returns: {'clients': [...], 'total_count': N, 'only_show_online': False}

# Online only
online = await client.list_clients(only_show_online=True)

Message Types

CommMsgType enum (use these, not strings):

Type Description
CommMsgType.TEXT Plain text
CommMsgType.JSON JSON string
CommMsgType.DICT Python dict
CommMsgType.BYTES Binary data
CommMsgType.IMAGE Image file
CommMsgType.FILE Regular file
CommMsgType.FOLDER Folder

Internal types (auto-handled): HEARTBEAT, LOGIN, LOGOUT, LIST_CLIENTS, LIST_CLIENTS_RESPONSE, LOGIN_RESPONSE

Message Listener Decorator

# Listen to specific type
@service.message_listener(msg_type=CommMsgType.TEXT)
async def handler(message):
    pass

# Listen from specific sender
@service.message_listener(msg_type=CommMsgType.FILE, from_client_id='specific_client')
async def handler(message):
    pass

# Listen to all types
@service.message_listener()
async def handler(message):
    pass

Note: Listeners automatically filter out messages sent by yourself.

File Download Control

File downloads are controlled via the listener's download_directory parameter:

# Auto-download files to ./downloads
@client.message_listener(msg_type=CommMsgType.FILE, download_directory="./downloads")
async def handle_file(message):
    # message.content contains downloaded file path
    print(f"Downloaded: {message.content}")

# No auto-download - saves bandwidth
@client.message_listener(msg_type=CommMsgType.FILE, from_client_id='low_priority')
async def handle_file(message):
    # message.content contains OSS key, not downloaded
    print(f"File available: {message.oss_key}")
    # Optionally: client.download_file_manually(message.oss_key, "./manual_downloads/")

Manual download

success = client.download_file_manually(
    oss_key="cross_comm/sender_id/123456_file.txt",
    save_directory="./downloads"
)

Message Object

@dataclass
class Message:
    msg_id: str                    # Unique message ID
    from_client_id: str            # Sender ID
    to_client_id: str              # 'all' or specific client ID
    msg_type: CommMsgType           # Message type enum
    content: Any                   # Message content
    timestamp: float                # Unix timestamp
    oss_key: Optional[str]         # OSS key for file transfers

    def to_dict(self) -> Dict:      # Convert to dict
    @classmethod
    def from_dict(cls, data) -> 'Message':  # Create from dict

Client ID Generation

If client_id is not specified, it's auto-generated using MAC address + UUID:

  • Format: {mac_address}_{uuid_suffix}
  • Example: a1b2c3d4e5f6_abc12345

Command Line

# Run server
python -m pywayne.cross_comm server

# Run client
python -m pywayne.cross_comm client

Important Notes

  • File transfer: Requires OSS environment variables; files auto-upload on send
  • Async required: All operations are async; use asyncio.run() or await in async context
  • Heartbeat: Auto-managed; adjust intervals for network conditions
  • Message filtering: Use download_directory to control auto-downloads and save bandwidth
  • State persistence: Server saves client status to cross_comm_clients.yaml
  • Role-specific methods: Server has start_server(), get_online_clients(); client has login(), logout(), send_message(), list_clients()

正文来自原始发布页, 版权归作者所有,许可未标注。 权利人认为有不妥,可申请下架。

标签

websocketreal-time-communicationaliyun-ossfile-transfercross-platformasynciotmessaging

同类 Skill