前言
补充上篇中python中yield和协程的协程内容
提示:以下是本篇文章正文内容,下面案例可供参考
一、协程的同步和异步
实例一(同步)
#! /usr/bin/python
# -*-coding: UTF-8 -*-
from gevent import monkey;monkey.patch_all()#如果不用gevent.sleep的话
import gevent
import time
from greenlet import greenlet
def task(pid):
time.sleep(0.5)
print("task %s is done"%pid)
def main():
#同步
for i in range(10):
task(i)
pass
if __name__=='__main__':
main()
运行结果为:
task 0 is done
task 1 is done
task 2 is done
task 3 is done
task 4 is done
task 5 is done
task 6 is done
task 7 is done
task 8 is done
task 9 is done
Process finished with exit code 0
实例二(异步)
#! /usr/bin/python
# -*-coding: UTF-8 -*-
from gevent import monkey;monkey.patch_all()#如果不用gevent.sleep的话
import gevent
import time
from greenlet import greenlet
def task(pid):
time.sleep(0.5)
print("task %s is done"%pid)
def main():
#异步
g_l = [gevent.spawn(task,i) for i in range(10)]
gevent.joinall(g_l)
print("main done")
pass
if __name__=='__main__':
main()
运行结果为:
task 0 is done
task 1 is done
task 2 is done
task 3 is done
task 4 is done
task 5 is done
task 6 is done
task 7 is done
task 8 is done
task 9 is done
main done
Process finished with exit code 0
二、协程实现网络通信
server.py:
#! /usr/bin/python
# -*- coding:UTF-8 -*-
#服务端程序
from gevent import monkey;monkey.patch_all()
from socket import *
import gevent
def server(server_ip,port):
s = socket(AF_INET,SOCK_STREAM)
s.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
s.bind((server_ip,port))
s.listen(5)
while True:
conn,addr = s.accept()
gevent.spawn(talk,conn,addr)
def talk(conn,addr):
try:
while True:
res = conn.revc(1024)
print("client %s:%s msg:%s"%(addr[0],addr[1],res.decode('utf-8')))
conn.send(res.upper())
except Exception as e:
print(e)
finally:
conn.close()
def main():
server('127.0.0.1',8088)
pass
if __name__ == '__main__':
main()
client.py:
#! /usr/bin/python
# -*- coding:UTF-8 -*-
from socket import *
#客户端程序
def main():
client = socket(AF_INET,SOCK_STREAM)
client.connect(('127.0.0.1',8088))
while True:
msg = input(">> ").strip()
if not msg:continue
client.send(msg.encode('utf-8'))
msg = client.recv(1024)
print(msg.decode('utf-8'))
pass
if __name__ == '__main__':
main()
运行结果为: