zoukankan      html  css  js  c++  java
  • python IO多路复用

    基于select

    作用:I/O多路复用是用于提升效率,单个进程可以同时监听多个网络连接IO。

    server端

    import select
    import socket
    
    sk = socket.socket()
    sk.bind(('127.0.0.1', 8010))
    sk.setblocking(False)
    sk.listen()
    
    read_lst = [sk]     #
    while True:   # [sk,conn]
        # select提供监听
        r_lst, w_lst, x_lst = select.select(read_lst, [], [])
        # print(read_lst)
        for i in r_lst:
            if i is sk:
                conn, addr = i.accept()
                read_lst.append(conn)
            else:
                ret = i.recv(1024)
                if ret == b'':
                    i.close()
                    read_lst.remove(i)
                    continue
                print(ret)
                i.send(b'bye!')

    client端

    import time
    import socket
    import threading
    
    
    def func():
        sk = socket.socket()
        sk.connect(('127.0.0.1', 8010))
        sk.send(b'hello')
        time.sleep(3)
        print(sk.recv(1024))
        sk.close()
    
    
    for i in range(5):
        threading.Thread(target=func).start()

    主要作用:定制异步框架

  • 相关阅读:
    python os
    [BZOJ2887] 旅行
    UVA1104 Chips Challenge
    CF364E Empty Rectangles
    CF1408H Rainbow Triples
    CF1214G Feeling Good
    CF506E Mr. Kitayuta's Gift
    采用Canal监听mysql数据库变化
    Java8 ParallelStream
    Java8 方法引用
  • 原文地址:https://www.cnblogs.com/wt7018/p/11624449.html
Copyright © 2011-2022 走看看