博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

协程实现多并发socket,跟NGINX一样

Posted on 2018-05-19 14:58  alex_hrg  阅读(223)  评论(0编辑  收藏  举报

server:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author aliex-hrg
import gevent
from gevent import socket
def server(port):
    s = socket.socket()
    s.bind(('0.0.0.0', port))
    s.listen(500)
    while True:
        conn,addr = s.accept()  #等待连接进来,没有连接一直挂起
        gevent.spawn(func,conn) #进来连接了,交给协程执行func函数,func无限收发数据,这中间遇到io切换
def func(conn):
    try:
        while True:
            recv = conn.recv(8096)
            print("recv:%s" %recv.decode())
            resp = recv.decode().upper()
            conn.send(resp.encode())
    except Exception as e:
        print(e)
    finally:
        conn.close()
if __name__ == '__main__':
    server(5000)

  client:

import socket
sock = socket.socket()
sock.connect(('127.0.0.1',5000))
flag = False
while not flag:
    data = input(">>:").strip()
    if len(data) == 0:continue
    sock.send(data.encode())  #如果是发送一个空值,虽然显示是发出去了,但对方却认为你没发
    recv_data = sock.recv(8096)
    print("recv:",recv_data.decode())
sock.close()