def producer():
g=consumer()
next(g)
for i in range(100):
print(\'alex_\',i)
g.send(i)
def consumer():
while True:
n = yield
print(\'egon_\',n)
producer()
from gevent import monkey;monkey.patch_all()
import gevent
from multiprocessing import Process
from socket import *
def server(ip,port):
s = socket(AF_INET, SOCK_STREAM)
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
s.bind((ip,port))
s.listen(5)
while True:
conn,addr=s.accept()
print(\'%s:%s\' % (addr[0], addr[1]))
g1=gevent.spawn(talk,conn,addr)
def talk(conn,addr):
while True:
try:
data=conn.recv(1024)
print(\'%s:%s [%s]\' %(addr[0],addr[1],data))
if not data:break
conn.send(data.upper())
except ConnectionResetError:
break
conn.close()
if __name__ == \'__main__\':
server(\'127.0.0.1\',8092)
客户端:
from threading import Thread
from socket import *
def client():
c=socket(AF_INET,SOCK_STREAM)
c.connect((\'127.0.0.1\',8092))
while True:
c.send(\'hello\'.encode(\'utf-8\'))
data=c.recv(1024)
print(data.decode(\'utf-8\'))
if __name__ == \'__main__\':
for i in range(500):
t=Thread(target=client)
t.start()
基于协程实现网络爬虫:
from gevent import monkey;monkey.patch_all()
import gevent
import requests
from threading import current_thread
def get(url):
print(\'%s get %s\' %(current_thread().getName(),url))
response=requests.get(url)
if response.status_code == 200:
return {\'url\':len(response.text)}
# print({\'url\':len(response.text)})
g1=gevent.spawn(get,\'http://www.baidu.com\')
g2=gevent.spawn(get,\'http://www.python.org\')
g3=gevent.spawn(get,\'http://www.jd.com\')
g1.join()
g2.join()
g3.join()
print(g1.value)
print(g2.value)
print(g3.value)