python 并发编程 基于gevent模块实现并发的套接字通信

 

 

之前线程池是通过操作系统切换线程,现在是程序自己控制,比操作系统切换效率要高

 

服务端

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

def communicate(conn):
    ''' 通信功能 '''
    while True:
        try:
            data = conn.recv(1024)
            if not data:break
            conn.send(data.upper())

        except ConnectionResetError:
            break

    conn.close()

def server(ip,port):
    ''' 负责建立连接 accept'''

    server = socket(AF_INET, SOCK_STREAM)
    server.bind((ip,port))
    server.listen(5)

    while True:
        conn,addr = server.accept()
        c = gevent.spawn(communicate,conn)

    server.close()


if __name__ == "__main__":
    g = gevent.spawn(server,'127.0.0.1', 8080)
    g.join()

 

客户端给服务端发送500个并发量,会看到一直不停的收消息

from socket import *
from threading import Thread
from threading import current_thread


def client():
    client = socket(AF_INET, SOCK_STREAM)
    client.connect(('127.0.0.1', 8080))

    while True:
        client.send(("%s say helo" % current_thread().getName()).encode("utf-8"))
        data = client.recv(1024)
        print(data.decode("utf-8"))

    client.close()

if __name__ == "__main__":
    for i in range(500):
        t = Thread(target=client,)
        t.start()

 

posted @ 2019-07-27 18:10  minger_lcm  阅读(187)  评论(0编辑  收藏  举报