TCP单线程实现并发

服务端

from gevent import monkey;monkey.patch_all()
import socket
from gevent import spawn


server = socket.socket()
server.bind(('127.0.0.1',8080))
server.listen(5)


def talk(conn):
    while True:
        try:
            data = conn.recv(1024)
            if len(data) == 0:break
            print(data.decode('utf-8'))
            conn.send(data.upper())
        except ConnectionResetError as e:
            print(e)
            break
    conn.close()

def server1():
    while True:
        conn, addr = server.accept()
        spawn(talk,conn)

if __name__ == '__main__':
    g1 = spawn(server1)
    g1.join()

 客户端

import socket
from threading import Thread,current_thread


def client():
    client = socket.socket()
    client.connect(('127.0.0.1',8080))
    n = 0
    while True:

        data = '%s %s'%(current_thread().name,n)
        client.send(data.encode('utf-8'))
        res = client.recv(1024)
        print(res.decode('utf-8'))
        n += 1

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

 

posted @ 2019-08-15 18:54  waller  阅读(270)  评论(0编辑  收藏  举报