• 举例一个IO多路复用的C/S例子


    #!/usr/bin/env python
    #-*-coding:utf-8 -*-
    
    import socket
    
    sk=socket.socket()
    
    sk.connect(("127.0.0.1",8090))
    while 1:
        inp=input(">>>")
        sk.send(inp.encode("utf8"))
        data=sk.recv(1024)
        print(data.decode("utf8"))
    
    # import socket
    #
    # sk=socket.socket()
    #
    # sk.connect(("127.0.0.1",9904))
    #!/usr/bin/env python
    #-*-coding:utf-8 -*-
    
    import selectors
    import socket
    
    sel = selectors.DefaultSelector()      # IO多路复用的方式有三种,这里根据操作系统拿一个
    
    def accept(sock, mask):
        conn, addr = sock.accept()  # Should be ready
        print('accepted', conn, 'from', addr)
        conn.setblocking(False)
        sel.register(conn, selectors.EVENT_READ, read)          # 将conn与read函数绑定,一旦conn被触发,与它有关系的就是read
    
    def read(conn, mask):
        try:
            data = conn.recv(1000)  # Should be ready
            if not data:
                raise Exception
            print('echoing', repr(data), 'to', conn)
            conn.send(data)  # Hope it won't block
        except Exception as e:
            print('closing', conn)
            sel.unregister(conn)
            conn.close()
    
    
    sock = socket.socket()
    sock.bind(('localhost', 8090))
    sock.listen(100)
    sock.setblocking(False)          # 设置非阻塞
    
    sel.register(sock, selectors.EVENT_READ, accept)      # 将创建的sock对象进行注册,与accept函数绑定
    print("server.....")
    
    while True:
        events = sel.select()     #[sock,..,conn2]
        for key, mask in events:
            callback = key.data           # callback就是之前绑定的函数名accept(conn变化前)
            callback(key.fileobj, mask)   # key.fileobj就是服务器的sock对象(conn变化前)
    
    # import socket
    # import select
    # sk=socket.socket()
    # sk.bind(("127.0.0.1",9904))
    # sk.listen(5)
    
    # while True:
    #     r,w,e=select.select([sk,sk],[],[],5)
    #     r=[sk,]
    #     for i in r:
    #         conn,add=i.accept()
    #         print(conn)
    #         print("hello")
    #
    #     print('>>>>>>')
  • 相关阅读:
    JavaScript笔记三两个
    形式参数分别是基本类型和引用类型的调用
    if (strAreaCode.Find("体检")>=0)
    C++编写DLL文件
    error LNK2001: unresolved external symbol __imp__closesocket@4
    accept函数
    socket编程
    MFC控件使用大全
    DLL导出函数
    LINK : fatal error LNK1104: cannot open file的解决方法
  • 原文地址:https://www.cnblogs.com/maxiaonong/p/9538582.html
Copyright © 2020-2023  润新知