• 基于selector的socket并发


    server:

    #!_*_coding:utf-8_*_
    #__author__:"Alex huang"
    import selectors  #selector模块集成了select,epoll,优先使用epoll,如果系统支持,windows不支持epoll
    import socket
    
    def accept(s,mask):   #这个回调函数实现建立N个并发连接
        conn,addr = s.accept()
        print("established to ",addr)
        conn.setblocking(False)
        sel.register(conn,selectors.EVENT_READ,handle) #将连接加入selector并回调handle
    def handle(conn,mask):    #要实现的功能写在这个回调函数内
        data = conn.recv(1024)
        if data:
            print("recv:",data.decode())
            re_data = data.decode().upper()
            conn.send(re_data.encode())
        else:
            print("closed conn...")
            sel.unregister(conn)  #关闭连接
            conn.close()
    sel = selectors.DefaultSelector()
    s = socket.socket()
    s.bind(("0.0.0.0",5000))
    s.listen(5)
    sel.register(s,selectors.EVENT_READ,accept)   #第一次回调accept,s是传给执行函数accept的参数
    
    while True:
        events = sel.select()  #默认阻塞,有连接时就返回活动的连接列表
        for key,mask in events:
            callback = key.data
            callback(key.fileobj,mask)
    

      client:

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    # author aliex-hrg
    __author__ = "alex"
    import socket
    import sys
    messages = [ 'This is the message. ',
                 'It will be sent ',
                 'in parts.',
                 'the end of'
                 ]
    server_address = ('192.168.80.100', 5000)
    # Create a TCP/IP socket
    socks = [ socket.socket(socket.AF_INET, socket.SOCK_STREAM) for i in range(10000) ] #模拟10000个会话
    # Connect the socket to the port where the server is listening
    print('connecting to %s port %s' % server_address)
    for s in socks:
        s.connect(server_address)
    
    for message in messages:
    
        # Send messages on both sockets
        for s in socks:
            print('%s: sending "%s"' % (s.getsockname(), message) )
            s.send(message.encode())
    
        # Read responses on both sockets
        for s in socks:
            data = s.recv(1024)
            print( '%s: received "%s"' % (s.getsockname(), data) )
            if not data:
                print(sys.stderr, 'closing socket', s.getsockname() )
    

      ...

  • 相关阅读:
    9.类与对象二----重载、值传递、可变个数形参
    1.数据库相关概念
    8.类与对象一举例
    7.类与对象一
    Educational Codeforces Round 91 (Rated for Div. 2) B. Universal Solution(思维)
    VS Code配置C++环境: Unable to start debugging. Unexpected GDB output from command报错
    Codeforces Round #655 (Div. 2) C. Omkar and Baseball(思维)
    Redis高可用,高性能,高并发
    .Net Core 中GC的工作原理
    大数据环境下该如何优雅地设计数据分层
  • 原文地址:https://www.cnblogs.com/alex-hrg/p/9081750.html
Copyright © 2020-2023  润新知