利用协程和socket实现并发

2019/05/09 19:57
阅读数 0

服务端代码

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


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

def server():
    server = socket.socket()
    server.bind(("127.0.0.1",8080))
    server.listen(5)
    while True:
        conn,addr = server.accept()
        spawn(communicate())
if __name__ == '__main__':
    s1 = spawn(server)
    s1.join()

客户端代码

import socket
from threading import  Thread,current_thread


def client():
    client = socket.socket()
    client.bind(("127.0.0.1",8080))
    n = 1
    while True:
        data = "%s %s "%(current_thread().name,n)
        n +=1
        client.send(data.encode("utf-8"))
        info = client.recv(1024)
        print(info)
if __name__ == '__main__':
    for i in range(500):
        t = Thread(target=client)
        t.start()
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部