websocket client or server, easy to use.
Project description
SocketMan
- 对 websockets 包的易用封装。
- 在独立线程中封装了协程
- 可以非阻塞方式交互
- 符合面向过程习惯的send、recv方法
应用场景示例
- 针对flask+werkzeug的单线程模式服务器无法使用服务websocket的问题,创建独立的websocket服务。
使用方法
启动线程(服务端)
serv = WebsocketServer('0.0.0.0', 5001)
serv.start()
客户端访问地址,服务未运行时为None
print(serv.url)
设置处理接收消息的回调函数
# 有消息传入时会随消息附带wsid, wsid为传入消息的连接编号
@serv.ON_RECV
def func( txt, wsid):
print(txt)
用recv方法接收,默认阻塞(不推荐)
serv.recv()
# 当设置wsid!=None时只接收对应wsid连接发送的数据
# block=False为非阻塞模式,无消息返回None
# 接收过程中连接关闭则raise一个RuntimeError
serv.recv(wsid=None, block=True)
发送消息到客户端
# 单个连接可以不带wsid参数,即wsid默认为None时将对所有连接广播消息
serv.send(txt)
serv.send(txt, wsid=None)
关闭线程
# 注意,线程启动关闭是一次性行为,如需再次使用需要重新实例化
serv.stop()
检查是否已在运行
serv.is_alive()
启动线程(客户端)
客户端与服务端的调用逻辑基本一致
client = WebsocketClient('ws://localhost:5001')
client.start()
设置处理接收消息的回调函数
@client.ON_RECV
def func( txt ):
print(txt)
用recv方法接收,默认阻塞(不推荐)
client.recv()
发送消息到服务端
client.send(txt)
关闭线程
# 注意,线程启动关闭是一次性行为,如需再次使用需要重新实例化
client.stop()
检查是否已在运行
client.is_alive()
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
socketman-0.1.2.tar.gz
(4.8 kB
view details)
Built Distribution
File details
Details for the file socketman-0.1.2.tar.gz
.
File metadata
- Download URL: socketman-0.1.2.tar.gz
- Upload date:
- Size: 4.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/4.0.2 CPython/3.10.11
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 7c79b1ee656409c33ff1a9337b5af48cf10ec435185a4ff7efc0403740ad13d6 |
|
MD5 | 80eb14b455e8d35ed902c7564fde4b10 |
|
BLAKE2b-256 | 30933c6112397e5d5eb91fed07191bca91e7fabb44c0e0b3a07a8fff503c0012 |
File details
Details for the file socketman-0.1.2-py3-none-any.whl
.
File metadata
- Download URL: socketman-0.1.2-py3-none-any.whl
- Upload date:
- Size: 5.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/4.0.2 CPython/3.10.11
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 621ce94a15bae3b394bac72f1b30f77a803cf5876aa828aa05103c80fef6b505 |
|
MD5 | fc15a3c3405b71f0fda2d8f7736f0b40 |
|
BLAKE2b-256 | 1b2879f0c3b443df1edf9e96d3bef56ad1976f0e07fcc1a6a06d11d08b34321b |