python3.4通过协程使用websockets
1.event loop
1.这里的事件循环类似javascript中的时间循环,在线程中执行协程需要有调度程序,协程是用户级的线程,不涉及内核级别的上下文切换,所以相对执行效率更高,协程都是在单个线程中被创建,在主线程中使用多协程比多线程更高效,需要将协程加入
2.任务和协程
2.1运行协程提供了三种方式:
(1)asyncio.run()
(2)yield from/await
(3)asyncio.create_task()
2.2从例程时序图下手,将能够快速的掌握协程的执行过程。从事件循环开始,将协程函数加入到任务中,print_sum开始执行,print_sum等待compute的结果,sleep等待期间执行权限又回到了EventLoop,1秒后执行权限又给到了compute()返回结果给到print_sum(),Event Loop中执行的就是一个的任务,任务中执行有多个协程函数,在调用协程函数时,需要使用yield from 进行等待,否则不会执行该协程函数。
3.python3.4协程调用websockets实现客户端
python3.5之前的版本使用协程的接口和3.5之后的版本不太相同,@asynciio.coroutine被async替代,yield from被await替代
import websockets
class Client(metaclass=Singleton):
@asyncio.coroutine
def connect(self):
try:
self.ws=yield from websockets.connect("ws://127.0.0.1:10079",extra_headers={"user-agent":"test"})
yield from self.recv()
except Exception as ex:
#print(ex)
pass
@asyncio.coroutine
def recv(self):
while True:
msg=yield from self.ws.recv()
print(msg)
def run(self):
#连接server
while True:
yield from self.connect()
def start(self):
#asyncio.run(self.run())
loop = asyncio.get_event_loop()
loop.run_until_complete(self.run())
loop.run_forever()