编程语言
首页 > 编程语言> > python-以协程gevent方式构建socket

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)

标签:__,socket,python,0.0,以协程,gevent,data,conn
来源: https://blog.csdn.net/a157215961/article/details/121589471