python--gevent高并发socket

时间:2022-02-10 22:24:53

server:

import sys
import socket
import time
import gevent
from gevent import socket,monkey

monkey.patch_all()


def server(port):
    try:
        s = socket.socket()
        s.bind(('0.0.0.0',port))
        s.listen(500)
        while True:
            cli, addr = s.accept()
            gevent.spawn(handle_request, cli)
    except KeyboardInterrupt as e:
        print(e)


def handle_request(conn):
    try:
        while True:
            print("before start recv")
            data = conn.recv(1024)
            print("after start recv")
            if not data:
                #print("client has been closed...")
                #conn.shutdown(socket.SHUT_RD)
                conn.close()
            else:
                print("recv:", data)
                conn.send(data)
    except OSError as e:
        print("client has been closed")

    except Exception as ex:
        print(ex)
    finally:
        conn.close()

if __name__ == '__main__':
    server(8001)

 

 

client:

import socket

HOST = 'localhost'
PORT = 8001
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
while True:
    msg = bytes(input(">>:"), encoding="utf-8")
    if msg == 'q'.encode("utf-8"):
        exit("退出!")
    s.sendall(msg)
    data = s.recv(1024)
    print('Received',repr(data))
s.close()