cushy-socket 一款轻量级的Python Socket框架

本文选取自笔者博客 https://www.blog.zeeland.cn/archives/3oi109x

简介

cushy-socket是一个轻量级的Python socket库,相较于传统的socket库,cushy-socket可以创建一个TCP/UDP程序。

项目地址:https://github.com/Undertone0809/cushy-socket

特性

  • 轻松发送Socket消息
  • 监听Socket消息并支持回调
  • 支持给客户端发送群体消息
  • 支持装饰器版本的监听
  • 监听主题消息并回调
  • 方便实现和管理多个socket连接

快速上手

 install cushy-socket --upgrade 

这里有一些使用cushy-socket的最小示例程序:一个回显所有接收到的数据的服务程序(仅为一个客户端提供服务),以及使用此程序的客户端。

  • 现在让我们来构建一个简单的ECHO demo。第一个示例仅支持IPv4。
# echo tcp server program
import socket
from cushy_socket.tcp import CushyTCPServer

cushy_tcp_server = CushyTCPServer(host='localhost', port=7777)
cushy_tcp_server.run()


@cushy_tcp_server.on_connected()
def handle_on_connected(sock: socket.socket):
    print(f"[server decorator callback] new client connected.")
    print(sock)


@cushy_tcp_server.on_disconnected()
def handle_on_disconnected(sock: socket.socket):
    print(f"[server decorator callback] a client disconnected.")
    print(sock)


@cushy_tcp_server.on_message()
def handle_msg_from_client(msg: str):
    print(f"[server decorator callback] cushy_tcp_server rec msg: {
      
      msg}")
    cushy_tcp_server.send("hello, I am server")

# echo tcp client program
from cushy_socket.tcp import CushyTCPClient

cushy_tcp_client = CushyTCPClient(host='localhost', port=7777)
cushy_tcp_client.run()


@cushy_tcp_client.on_connected()
def handle_on_connected():
    print(f"[client decorator callback] connect to server.")


@cushy_tcp_client.on_disconnected()
def handle_on_disconnected():
    print(f"[client decorator callback] server disconnected.")


@cushy_tcp_client.on_message()
def handle_msg_from_server(msg: str):
    print(f"[client decorator callback] cushy_tcp_client rec msg: {
      
      msg}")


cushy_tcp_client.send("hello, here is CSTCP client")
cushy_tcp_client.close()

待办

  • 支持更多的生命周期回调
  • 优化Socket关闭的处理
  • 优化语法表达式
  • 添加UDP服务器/客户端支持
  • 提供更多解决方案
  • 提供更多异步支持
  • 提供更多装饰器支持
  • 优化单元测试
  • 发送和监听主题消息

贡献

如果您想为这个项目做出贡献,您可以提交pr或问题。我很高兴看到更多的人参与并优化它。

猜你喜欢

转载自blog.csdn.net/linZinan_/article/details/129456563