gevent实现套接字
server-------------
#!/usr/bin/env python
# encoding: utf-8
# Date: 2018/6/17
from gevent import monkey,spawn;monkey.patch_all()
from socket import *
# 负责通信
def communicate(conn):
while True:
try:
data = conn.recv(1024)
if not data: break
conn.send(data.upper())
except ConnectionResetError:
break
conn.close()
# 建立链接
def server(ip, port):
server = socket(AF_INET, SOCK_STREAM)
server.bind((ip, port))
server.listen(5)
while True:
conn, addr = server.accept()
spawn(communicate, conn) # 启动协程,这里不需要join,因为这里提交完,线程不会结束
server.close()
if __name__ == '__main__':
g = spawn(server, '127.0.0.1', 8080)
g.join()
client------------
#!/usr/bin/env python
# encoding: utf-8
# Date: 2018/6/17
# 客户端可以启动多个进程,启动一个就是一个进程
from socket import *
from threading import Thread,currentThread
def client():
client = socket(AF_INET, SOCK_STREAM)
client.connect(('127.0.0.1', 8080))
while True:
client.send(('% s hello' % currentThread().getName()).encode('utf-8'))
data = client.recv(1024)
print(data.decode('utf-8'))
if __name__ == '__main__':
for i in range(500):
t = Thread(target=client)
t.start()
# 目前,服务端一个线程,可以抗住客户端500线程并发,
# 如果再加上多进程,每个进程再开多个线程,每个线程再基于gevent模块把io解决了,程序效率就相当牛逼了