python使用gevent使用套接字并发通讯建立sever连接

用户头像
大鱼
2019:08:06 17:42:57  阅读: 35  喜欢:

server

# 使用gevent使用套接字并发通讯
import socket
from gevent import monkey, spawn
monkey.patch_all()

def receive_message(conn, addr):
    print(conn, addr)
    while 1:
        message = conn.recv(1024)
        print(message.decode('utf-8'))
        if not message: break
    print('连接断开')


def run_server():
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    host, port = '127.0.0.1', 8888

    server.bind((host, port))

    server.listen(5)
    while True:
        conn, addr = server.accept()
        g2 = spawn(receive_message, conn, addr)


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

client

import socket
from concurrent.futures import ThreadPoolExecutor
from threading import current_thread

def connect_server(x):
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    host, port = '127.0.0.1', 8888
    client.connect((host, port))

    while True:
        client.send('hello --{}\r\n'.format(current_thread().getName()).encode('utf-8'))


if __name__ == '__main__':
    t_pool = ThreadPoolExecutor(100)
    for x in range(100):
        t_pool.submit(connect_server, x)
新的评论