9
分享一下完全不依赖 asyncio 也支持异步语法的库
source link: https://www.v2ex.com/t/800308
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
https://github.com/snower/sevent
异步语法的支持完全不依赖 asyncio,当然并没有说可以替代 asyncio 或者更好啥的,只是一种实现,如果有对异步 io 或者 python 异步语法实现感兴趣的可以一看吧。
只要是用于代理流量转发这样的场景,所以接口毕竟简单,当然支持范围也就没 asyncio 那么广了,从 echo 测试来看,性能还是要好于 asyncio 一些的,helpers 中也简单实现了几个工具。
HTTP 请求测试
import sevent
async def http_test():
s = sevent.tcp.Socket()
await s.connectof(('www.baidu.com', 80))
await s.send(b'GET / HTTP/1.1\r\nHost: www.baidu.com\r\nConnection: Close\r\nUser-Agent: curl/7.58.0\r\nAccept: */*\r\n\r\n')
data = b''
while True:
try:
data += (await s.recv()).read()
except sevent.tcp.SocketClosed:
break
print(data.decode("utf-8"))
await s.closeof()
sevent.run( http_test)
TCP 端口转发
import sys
import sevent
async def tcp_port_forward_server():
server = sevent.tcp.Server()
server.listen(("0.0.0.0", int(sys.argv[1])))
while True:
conn = await server.accept()
pconn = sevent.tcp.Socket()
pconn.connect((sys.argv[2], int(sys.argv[3])))
conn.link(pconn)
sevent.run(tcp_port_forward_server)
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK