Python asyncio
#!/usr/bin/env python
# WS server that sends messages at random intervals
import asyncio
import datetime
import random
import websockets
async def time(websocket, path):
while True:
now = datetime.datetime.utcnow().isoformat() + 'Z'
await websocket.send(now)
await asyncio.sleep(random.random() * 3)
start_server = websockets.serve(time, '127.0.0.1', 5678)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
#!/usr/bin/env python
# WSS (WS over TLS) client example, with a self-signed certificate
import asyncio
import pathlib
import ssl
import websockets
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
ssl_context.load_verify_locations(
pathlib.Path(__file__).with_name('localhost.pem'))
async def hello():
async with websockets.connect(
'wss://localhost:8765', ssl=ssl_context) as websocket:
name = input("What's your name? ")
await websocket.send(name)
print(f"> {name}")
greeting = await websocket.recv()
print(f"< {greeting}")
asyncio.get_event_loop().run_until_complete(hello())
这两段python使用了asyncio事件循环,本质上是一个event-loop的实现,安排任务,等待Future从而做到在单线程中的async/await语法。
这里的Future相当于js中的promise,也就是将来返回的值。
这里的run_until_complete需要一个Future对象,它会把这个参数丢进去运行。
如果是希望non-blocking,可以改用ensure_future来执行。run_until_complete会阻塞原有的线程。