【select模块】select IO多路复用和select实现FTP
admin
2023-07-23 18:01:51
0

select是全平台通用的IO多路复用模块。最大连接数:1024。

poll和epoll没有最大连接数限制,但只能用在linux平台。

selectors是再封装模块,推荐使用。下篇会讨论。

select.select(rlist, wlist, xlist[, timeout])

  • This is a straightforward interface to the Unix select() system call. The first three arguments are sequences of ‘waitable objects’: either integers representing file descriptors or objects with a parameterless method named fileno() returning such an integer:

    Empty sequences are allowed, but acceptance of three empty sequences is platform-dependent. (It is known to work on Unix but not on Windows.)  The optional timeout argument specifies a time-out as a floating point number in seconds.  When the timeout argument is omitted the function blocks until at least one file descriptor is ready.  A time-out value of zero specifies a poll and never blocks.

    The return value is a triple of lists of objects that are ready: subsets of the first three arguments.  When the time-out is reached without a file descriptor becoming ready, three empty lists are returned.

    Among the acceptable object types in the sequences are Python file objects (e.g. sys.stdin, or objects returned by open() or os.popen()), socket objects returned by socket.socket().  You may also define a wrapper class yourself, as long as it

    • rlist: wait until ready for reading

    • wlist: wait until ready for writing

    • xlist: wait for an “exceptional condition” (see the manual page for what your system considers such a condition)

方法、属性参数作用示例
select(rlist,wlist,rlist,[timout=1])



poll()
没人用了,已经升级为epoll


epoll(sizehint = -1,flags=0)

sizehint informs epoll about the expected number of events to be registered.  It must be positive, or-1to use the default. It is only used on older systems where epoll_create1() is not available; otherwise it has no effect (though its value is still checked).

flags is deprecated and completely ignored.  However, when supplied, its value must be 0 or select.EPOLL_CLOEXEC, otherwise OSError is raised.


(Only supported on Linux 2.5.44 and newer.) Return an edge polling object, which can be used as Edge or Level Triggered interface for I/O events.

devpoll()

 

(Only supported on Solaris and derivatives.)  Returns a /dev/poll polling object; see section /dev/poll Polling Objects below for the methods supported by devpoll objects.
kevent()

select.kevent(ident, filter=KQ_FILTER_READ, flags=KQ_EV_ADD, fflags=0, data=0, udata=0)
  • (Only supported on BSD.)  Returns a kernel event object; see section Kevent Objects below for the methods supported by kevent objects.


kqueue()
(Only supported on BSD.)  Returns a kernel queue object; see section Kqueue Objects below for the methods supported by kqueue objects.


import socket
import os
import select
import queue
import json


class SelectFTP(object):
    def __init__(self, ip, port):
        self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server.setblocking(0)
        self.server.bind((ip, port))
        self.server.listen(20)
        

        self.inputs = [self.server]
        self.outputs = []
        self.file_attr = {}
        # file_attr format:file_attr[socket]:{func:'', filename:'', len:999, recv_len:0}      
        self.socket_queue = {}

    
    def upload(self, sock, write_data):
        # if os.path.isfile(self.file_attr[sock]['filename']):
        with open(self.file_attr[sock]['filename'], 'a+') as file:
            file.write(data)
            self.file_attr[sock][recv_len] += len(write_data)
            if self.file_attr[sock][recv_len] == self.file_attr[sock][len]:
                del self.file_attr[sock]
                file.close()
        
   
    def download(self, sock, *args):
        pass
        
    def run(self):
        while self.inputs:
            read_active, read_output, exception = select.select(self.inputs, self.outputs, self.inputs)
            
            for fd in read_active:
                if fd is server:
                    conn, addr = fd.accept(1024)
                    conn.setblocking(0)
                    self.inputs = self.inputs.append(conn)
                    self.socket_queue[fd] = queue.Queue()
                    
                else:
                    recv_data = fd.recv(1024)

                    if recv_data:
                        data = json.loads(recv_data.decode())
                        
                        if fd not in self.file_attr.keys:
                            self.file_attr[fd] = data
                        
                        else:
                            try:
                                self.socket_queue.put_nowait(data)
                                if fd not in self.outputs:
                                    self.outputs.append(fd)
                            except Exception as e:
                                print(e)
                            
                    else:
                        self.inputs.remove(fd)
                        if fd in self.outputs:
                            self.outputs.remove(fd)
                        del self.socket_queue[fd]
                        
                    send_data = 
                        
            for fd in read_output:
                try:
                    message = self.socket_queue.get_nowait()
                except queue.Empty:
                    self.outputs.remove(fd)
                    print('wait...')
                else:
                    getattr(self.file_attr[fd]['func'])(fd, message)

 

相关内容

热门资讯

北约秘书长到访白宫造新词“特万... 当地时间6月24日,北约秘书长马克·吕特近日到访白宫,与美国总统唐纳德·特朗普举行会晤。在伊朗局势等...
北京:第四届链博会首设人工智能... 本文转自【人民网-图片频道】; 2026年6月23日,北京,在第四届中国国际供应链促进博览会数智科...
【西街观察】AI比拼亦在AI之... AI一直是各类峰会论坛的顶流议题,而参数竞赛与算法突破之外,正在进行的夏季达沃斯论坛提供了另一种解题...
【微特稿】机翼出现裂纹 空客紧... 【新华社微特稿】欧洲飞机制造商空中客车公司23日说,该公司将对阿联酋航空公司和澳大利亚澳洲航空公司旗...
红米K90至尊版参数曝光,骁龙... REDMI K90至尊版定档6月30日发布,核心参数与外观提前在网上曝光。核心搭载骁龙8 Elite...
豆包收费版,正把WPS逼近死角 6月21日,#被WPS背刺了# 已经挂上了热搜——大量用户发现,就算把WPS装进D盘E盘,它的缓存和...
逐浪数字蓝海,运河湾迈向数字视... (来源:嘉兴日报) 转自:嘉兴日报 ■记者 戴瑞雪 通讯员 计 亲 图片由受访单位提供 当江...
史上最大!荣耀研发14000m... 快科技6月24日消息, 荣耀WIN系列于去年12月亮相,首发搭载了10000mAh青海湖大电池,一举...
原创 月... 牛津大学的一位天体物理学家公开提出,找外星文明这件事,也许不必把希望都押在遥远的星空上,咱们家门口的...
药食同源 路向何方 6月23日,顾客在郑州东济堂体验药食同源餐饮。河南日报全媒体记者 聂冬晗 摄洛阳市瀍河回族区中原美谷...