当前位置: 首页>>代码示例>>Python>>正文


Python ThreadPool.execute方法代码示例

本文整理汇总了Python中ThreadPool.ThreadPool.execute方法的典型用法代码示例。如果您正苦于以下问题:Python ThreadPool.execute方法的具体用法?Python ThreadPool.execute怎么用?Python ThreadPool.execute使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ThreadPool.ThreadPool的用法示例。


在下文中一共展示了ThreadPool.execute方法的1个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: pool

# 需要导入模块: from ThreadPool import ThreadPool [as 别名]
# 或者: from ThreadPool.ThreadPool import execute [as 别名]
class TCPServer:
    """Server class. Creates, binds, and listens using server socket,
    For every client that connects, its information is passed to a thread in a thread pool (see: ThreadPool.py)
    """
    def __init__(self, server_addr, server_port):
        self.server_port = server_port
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.s.bind((server_addr, server_port))
        self.pool = ThreadPool(10) #start with 10 threads
        self.num_clients = 0
        self.client_limit = CLIENT_LIMIT
        #Dictionary used to map string representations of commands to functions which will perform the command
        #Commands are functions listed in commands.py
        self.command_map = {
            "KILL_SERVICE": self.kill_service,
            "HELO": self.echo,
            "JOIN_CHATROOM": self.join_chatroom,
            "LEAVE_CHATROOM": self.leave_chatroom,
            "DISCONNECT": self.disconnect,
            "CHAT": self.chat
        }
        self.chat_room_locks = []
        self.chat_rooms = []
        self.chat_room_map = {} #map a string name to integer index of the chatroom in chat_rooms
        signal.signal(signal.SIGINT, exit_handler)



    def listen(self):
        """Listen for connections and delegate to thread pool upon connection
        """
        self.s.listen(5)
        while True:
            (client_s, client_addr) = self.s.accept()
            print "SERVER_INFO: Client connected from: {0}".format(client_addr)
            full = self.num_clients + 1 > self.client_limit
            if full == True:
                print "server full"
                client_s.close()
            else:
                self.pool.execute(self.connection_handler, client_s, client_addr)
                self.num_clients += 1
            if self.num_clients > 30 and self.pool.num_threads < 25: #magic number as basic implementation
                self.pool.add_threads(10)
            elif self.num_clients < 20 and self.pool.num_threads > 35:
                self.pool.remove_threads(10)

            print "Clients: {0}".format(self.num_clients)

    def connection_handler(self, socket, addr):
        """Function passed to thread pool which actively deals with clients"
        Continuously receives messages, parses them into a command and command argument, and calls the
        appropriate function using the dictionary defined above
        """
        print "Connection handler"
        s = socket
        while True:
            #if the connection is cut between server and client the server may hold an incorrect count of the current number of clients. this should be fixed by some protocol for determining if clients are connected (a heartbeat)
            try:
                msg_raw = s.recv(2048)
            except SocketError: #s.close()
                s.close()
                self.num_clients -= 1
                return False
            else: #client just disconnected
                if not msg_raw:
                    self.num_clients -= 1
                    s.close()
                    return False

            cmd_arg_dict = utils.split_msg(msg_raw)
            (cmd, arg) = cmd_arg_dict.items()[0]
            print "CMD " + cmd
            if cmd in self.command_map.keys():
                self.command_map[cmd](socket=s, addr=addr, args=cmd_arg_dict, student_id=STUDENT_ID)

    def kill_service(self, **kwargs):
        print "SERVER_INFO: Kill command issued. Server shutting down....\n"
        os.kill(os.getpid(), signal.SIGHUP)
    
    def echo(self, **kwargs):
        print "SERVER_INFO: Echo (HELO) command issued"
        s = kwargs.get("socket", None)
        (ip, port) = kwargs.get("addr", None)
        args = kwargs.get("args", None)
        return_string = args["HELO"]
        student_id = kwargs.get("student_id", None)
    
    
        reply = "HELO {0}\nIP:{1}\nPort:{2}\nStudentID:{3}\n".format(return_string, ip, port, student_id)
    
        try:
            s.send(reply)
        except Exception:
            print "SERVER_INFO: Error sending reply to client..."
    
    
    def join_chatroom(self, **kwargs):
        print "SERVER_MSG: join"
#.........这里部分代码省略.........
开发者ID:EEEden,项目名称:distributed,代码行数:103,代码来源:TCPServer.py


注:本文中的ThreadPool.ThreadPool.execute方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。