单线程下实现服务器的并发
import socket
import gevent
from gevent import monkey
monkey.patch_all()
def server():
s = socket.socket()
s.bind(('0.0.0.0',8080))
s.listen()
while True:
cli, addr = s.accept()
print('recv from ', addr)
gevent.spawn(requests, cli)
def requests(conn):
try:
while True:
data = conn.recv(1024)
print(data.decode())
conn.send(data.upper())
except ConnectionResetError as e:
print(e)
server()
客户端代码
import socket
client = socket.socket()
client.connect(('localhost', 8080))
while True:
data = input('>>>')
if not data:continue
client.send(data.encode())
print('>>>', client.recv(1024).decode())