欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python 之网络并发(非阻塞IO模型)

程序员文章站 2023-11-04 12:09:34
实现gevent模块 服务端: from socket import * import time s = socket() s.bind(('127.0.0.1',8080)) s.listen(5) s.setblocking(False) r_list=[] w_list=[] while Tr ......

实现gevent模块

服务端:

from socket import *
import time

s = socket()
s.bind(('127.0.0.1',8080))
s.listen(5)
s.setblocking(false)

r_list=[]
w_list=[]
while true:
    try:
        conn, addr = s.accept()
        r_list.append(conn)

    except blockingioerror:
        # time.sleep(0.05)
        print('可以去干其他的活了')
        print('rlist: ',len(r_list))

        # 收消息
        del_rlist=[]
        for conn in r_list:
            try:
                data=conn.recv(1024)
                if not data:
                    conn.close()
                    del_rlist.append(conn)
                    continue
                # conn.send(data.upper())
                w_list.append((conn,data.upper()))
            except blockingioerror:
                continue
            except connectionreseterror:
                conn.close()
                # r_list.remove(conn)
                del_rlist.append(conn)

        # 发消息
        del_wlist=[]
        for item in w_list:
            try:
                conn=item[0]
                res=item[1]
                conn.send(res)
                del_wlist.append(item)
            except blockingioerror:
                continue
            except connectionreseterror:
                conn.close()
                del_wlist.append(item)

        # 回收无用连接
        for conn in del_rlist:
            r_list.remove(conn)

        for item in del_wlist:
            w_list.remove(item)

客户端:

from socket import *
import os

client = socket()
client.connect(('127.0.0.1', 8080))

while true:
    data='%s say hello' %os.getpid()
    client.send(data.encode('utf-8'))
    res=client.recv(1024)
    print(res.decode('utf-8'))