zoukankan      html  css  js  c++  java
  • 基于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() )
    

      ...

  • 相关阅读:
    PAT1065. A+B and C (64bit)
    PAT1064. Complete Binary Search Tree
    PAT 1063. Set Similarity
    CodeForces
    Golang在京东列表页实践总结
    asp.net 5 如何使用ioc 以及在如何获取httpcontext对象
    陨石坑之webapi 使用filter中如何结束请求流
    陨石坑之webapi使用filter
    Socket通信前必须考虑的几件事
    ZeroMQ的进阶
  • 原文地址:https://www.cnblogs.com/alex-hrg/p/9081750.html
Copyright © 2011-2022 走看看