day33-3 用协程实现并发实例

基于协程的TCP并发编程

服务端

from gevent import monkey
monkey.patch_all()  # 一定要放在上面
import gevent
from socket import *


def runserver():
    server = socket()
    server.bind(('127.0.0.1', 8000))
    server.listen(5)
    print('start...')

    while True:
        conn, client_addr = server.accept()
        gevent.spawn(task, conn, client_addr)


def task(conn, client_addr):
    while True:
        try:
            data = conn.recv(1024)
            print(f'from {client_addr} data: {data.decode("utf8")}')

            conn.send(data.upper())
        except ConnectionResetError as e:
            break
    conn.close()


runserver()

客户端

from socket import *

client = socket()
client.connect(('127.0.0.1', 8000))

while True:
    msg = input('please enter msg:').strip()
    if not msg: continue
    client.send(msg.encode('utf8'))

    data = client.recv(1024)
    print('from server data:', data.decode('utf8'))
posted @ 2019-07-08 21:09  Never&say&die  阅读(120)  评论(0编辑  收藏  举报