2019.10.24TCP协程处理

server

from gevent import monkey,spawn
monkey.patch_all()

import socket
server = socket.socket()
server.bind(
    ('127.0.0.1',8888)
)

server.listen(5)
print('server on')

def worker(conn):
    while 1 :
        try :
            data = conn.recv(1024).decode('utf-8')
            if len(data) == 0:
                break
            print(data)
            conn.send(data.encode('utf-8'))

        except Exception as e:
            print(e)
            break

    conn.close()

def server2():
    while 1:
        conn,addr = server.accept()
        print(addr)
        spawn(worker,conn)

if __name__ == '__main__':
    s1 = spawn(server2)
    s1.join()

client

import socket
from threading import  Thread,current_thread
def client():
    client = socket.socket()
    client.connect(
        ('127.0.0.1',8888)
    )

    print('client on ')

    number = 0

    while 1:
        send_data = f'{current_thread().name} {number}'

        client.send(send_data.encode('utf-8'))

        data = client.recv(1024).decode('utf-8')
        print(data.upper())

        number += 1

for i in range(100):
    Thread(target=client).start()



posted @ 2019-10-24 21:30  Agsol  阅读(110)  评论(0编辑  收藏  举报