python-以协程gevent方式构建socket

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Vergil Fu

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

monkey.patch_all()
def server(port):
    s = socket.socket()
    s.bind(('0.0.0.0', port))
    s.listen(5000)
    while True:
        cli, addr = s.accept()
        gevent.spawn(handle_request, cli)#############################建立协程
def handle_request(conn):
    try:
        while True:
            data = conn.recv(1024)
            print("recv:", data)
            conn.send(data)
            if not data:
                conn.shutdown(socket.SHUT_WR)
    except Exception as  ex:
        print(ex)
    finally:
        conn.close()
if __name__ == '__main__':
    server(8090)

上一篇:数据分析--01股票分析


下一篇:MySQL_Ch8