Python socketserver.ThreadingTCPServer() Examples

The following are 24 code examples of socketserver.ThreadingTCPServer(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module socketserver , or try the search function .
Example #1
Source File: server.py    From bc18-scaffold with MIT License 7 votes vote down vote up
def start_viewer_server(port: int, game: Game) -> socketserver.BaseServer:
    '''
    Start a socket server for the players to connect to
    Args:
        port: port to connect to viewer on

        game: The game information that is being run

        use_docker bool: whether to use docker or not

    Return:
        server_thread: The connection so it can be closed by parent functions at
                        the appropriate time
    '''

    # Create handler for mangaing each connections to server
    receive_handler = create_receive_handler(game, {}, False, False)

    # Start server
    server = socketserver.ThreadingTCPServer(('localhost', port), receive_handler)
    server_thread = threading.Thread(target=server.serve_forever, daemon=True)
    server_thread.start()

    return server 
Example #2
Source File: matcher_queue.py    From osm-wikidata with GNU General Public License v3.0 6 votes vote down vote up
def main():
    HOST, PORT = "localhost", 6030

    overpass_thread = threading.Thread(target=process_queue_loop)
    overpass_thread.daemon = True
    overpass_thread.start()

    socketserver.ThreadingTCPServer.allow_reuse_address = True
    server = socketserver.ThreadingTCPServer((HOST, PORT), RequestHandler)
    ip, port = server.server_address

    server_thread = threading.Thread(target=server.serve_forever)
    server_thread.name = 'server thread'

    server_thread.start()
    print("Server loop running in thread:", server_thread.name)
    server_thread.join() 
Example #3
Source File: server.py    From Cooolis-ms with GNU General Public License v3.0 6 votes vote down vote up
def main():
    example = 'Example:\n\n$ python3 server.py -U msf -P msf -v -s -l 4444'
    args = ArgumentParser(prog='Cooolis-ms',epilog=example)
    args.add_argument('-U','--username',help='Metasploit web service username',required=True)
    args.add_argument('-P','--password',help='Metasploit web service password',required=True)
    args.add_argument('-H','--host',help='Metasploit web service host, Default: localhost',default='localhost')
    args.add_argument('-p','--port',help='Metasploit RPC service port, Default: 55553',default=55553,type=int)
    args.add_argument('-S','--server',help='Payload sender listen host, Default: localhost',default='localhost')
    args.add_argument('-l','--listen',help='Payload listen port, Default: 1111',default=1111,type=int)
    args.add_argument('-u','--uri',help='Metasploit RPC service uri, Default: /api/1.0/',default='/api/1.0/')
    args.add_argument('-t','--type',help='Payload Type',choices=('exe','ruby','c','dll','vbs','powershell'))
    args.add_argument('-s','--ssl',help='Enable ssl, Default: True',action="store_true",default=True)
    args.add_argument('-v','--versobe',help='Enable debug',action="store_true")
    parser = args.parse_args()
    print("[*]Server Host : {host} , Server Port : {port}".format(host=parser.server,port=parser.listen))
    server = ThreadingTCPServer((parser.server,parser.listen),Metasploit_RPC.Creator(parser))
    server.serve_forever() 
Example #4
Source File: pos.py    From py-bitcoin with GNU General Public License v3.0 6 votes vote down vote up
def run():
    # create a genesis block
    t = str(datetime.now())
    genesis_block = {
        "Index": 0,
        "Timestamp": t,
        "BPM": 0,
        "PrevHash": "",
        "Validator": ""
    }

    genesis_block["Hash"] = calculate_hash(genesis_block)
    print(genesis_block)
    block_chain.append(genesis_block)

    thread_canditate = threading.Thread(target=candidate, args=(candidate_blocks,), daemon=True)
    thread_pick = threading.Thread(target=pick_winner, args=(announcements,), daemon=True)

    thread_canditate.start()
    thread_pick.start()

    # start a tcp server
    serv = ThreadingTCPServer(('', 9090), HandleConn)
    serv.serve_forever() 
Example #5
Source File: RPCServer.py    From aitom with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, addr, requestHandler=RPCHandler, bind_and_activate=True):
        self.instance = None
        socketserver.ThreadingTCPServer.__init__(self, addr, requestHandler, bind_and_activate)
        self.previous_method = None
        self.same_method_call_count = 0
        self.process = psutil.Process(os.getpid()) 
Example #6
Source File: server.py    From chat with MIT License 5 votes vote down vote up
def start(host="localhost", port=7000):
    """Start NLU server.

    Create the server, binding to host and port. Then activate the server.
    This will keep running until you interrupt the program with Ctrl-C.

    Args:
        host: Server IP address. 服务器IP地址设置。
            Defaults to "localhost".
        port: server port. 服务器端口设置。
            Defaults to 7000.
    """
    # 多线程处理并发请求
    sock = socketserver.ThreadingTCPServer((host, port), MyTCPHandler)
    sock.serve_forever() 
Example #7
Source File: dm_log_server.py    From datman with Apache License 2.0 5 votes vote down vote up
def __init__(self, host, port, handler=LogRecordStreamHandler):
        socketserver.ThreadingTCPServer.__init__(self, (host, port), handler)
        self.abort = 0
        self.timeout = 1 
Example #8
Source File: test_socketserver.py    From android_universal with MIT License 5 votes vote down vote up
def test_ThreadingTCPServer(self):
        self.run_server(socketserver.ThreadingTCPServer,
                        socketserver.StreamRequestHandler,
                        self.stream_examine) 
Example #9
Source File: receivers.py    From multilog with MIT License 5 votes vote down vote up
def __init__(self, host=DEFAULT_HOST, port=DEFAULT_PORT, handler=LogHandler):
        """Initialize the log receiver

        :param host: The hostname to bind to
        :param port: The port to listen on
        :param handler: The handler to send received messages to

        """
        socketserver.ThreadingTCPServer.__init__(self, (host, port), handler)
        self.abort = 0
        self.timeout = 1
        self.logname = None 
Example #10
Source File: sourcetrail.py    From vim-sourcetrail with MIT License 5 votes vote down vote up
def start_server(cls):
        """starting the server to listen"""
        if cls.inst().__server is None:
            try:
                socketserver.ThreadingTCPServer.allow_reuse_address = True
                address = (Options.get_ip(), Options.get_port_sourcetrail_to_vim())
                cls.inst().__server = socketserver.ThreadingTCPServer(address, ConnectionHandler)
                server_thread = threading.Thread(target=cls.inst().__server.serve_forever)
                server_thread.daemon = True
                server_thread.start()
            except socket.error:
                print("Socket needed for Sourcetrail plugin already in use") 
Example #11
Source File: test_socketserver.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_ThreadingTCPServer(self):
        self.run_server(socketserver.ThreadingTCPServer,
                        socketserver.StreamRequestHandler,
                        self.stream_examine) 
Example #12
Source File: tcp.py    From encrypted-dns with Apache License 2.0 5 votes vote down vote up
def serve(host, port, wire_message_handler_object):
        """
        :param wire_message_handler_object: Instance of encrypted_dns.resolve.WireMessageHandler.
        :param host: Host address of Datagram Inbound Server.
        :param port: Port of Datagram Inbound Server.
        :return: Object reference of Datagram Inbound Server.
        """
        wire_message_handler.append(wire_message_handler_object)
        stream_inbound = socketserver.ThreadingTCPServer((host, port), StreamHandler)
        StreamInbound.setup(host, port)
        stream_inbound.serve_forever()
        return stream_inbound 
Example #13
Source File: net10_tcp_threading.py    From python_web_Crawler_DA_ML_DL with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def handle(self):
        """重载handle方法"""
        print(self.client_address, '连接了服务器')
        request_data = self.request.recv(2048).decode('utf-8')
        request_header_lines = request_data.splitlines()
        # print(request_header_lines[0])  # 第一行为请求头信息
        # 解析请求头,获取具体请求信息
        pattern = r'[^/]+(/[^ ]*)'
        request_html_name = re.match(pattern, request_header_lines[0]).group(1)
        # 根据解析到的内容补全将要读取文件的路径
        if request_html_name == '/':
            request_html_name = STATIC_PATH + 'baidu.html'
        else:
            request_html_name = STATIC_PATH + request_html_name

        # 根据文件情况来返回相应的信息
        try:
            html_file = open(request_html_name, 'rb')
        except FileNotFoundError:
            # 文件不存在,则返回文件不存在,并返回状态码404
            resp_headers = 'HTTP/1.1 404 not found\r\n'
            resp_headers += "Server: PWB" + str(VERSION) + '\r\n'
            resp_headers += '\r\n'
            resp_body = '==== 404 file not found===='.encode('utf-8')
        else:
            # 文件存在,则读取文件内容,并返回状态码200
            resp_headers = "HTTP/1.1 200 OK\r\n"  # 200代表响应成功并找到资源
            resp_headers += "Server: PWB" + str(VERSION) + '\r\n'  # 告诉浏览器服务器
            resp_headers += '\r\n'  # 空行隔开body
            resp_body = html_file.read()  # 显示内容为读取的文件内容
            html_file.close()
        finally:
            resp_data = resp_headers.encode('utf-8') + resp_body  # 结合响应头和响应体
            # 发送相应数据至浏览器
            self.request.send(resp_data)
            self.request.close()  # HTTP短连接,请求完即关闭TCP连接 
Example #14
Source File: server.py    From pyxform with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, port=8000):
        self._server_address = ("127.0.0.1", port)
        self._handler = SimpleHTTPRequestHandlerHere
        self.httpd = ThreadingTCPServer(
            self._server_address, self._handler, bind_and_activate=False
        ) 
Example #15
Source File: ssh_forward.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, remote_server, ssh_transport, *args, **kwargs):
		self.remote_server = remote_server
		self.ssh_transport = ssh_transport
		socketserver.ThreadingTCPServer.__init__(self, *args, **kwargs) 
Example #16
Source File: test_socketserver.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_ThreadingTCPServer(self):
        self.run_server(socketserver.ThreadingTCPServer,
                        socketserver.StreamRequestHandler,
                        self.stream_examine) 
Example #17
Source File: SimpleServer.py    From advancedpython3 with GNU General Public License v3.0 5 votes vote down vote up
def main():
    print('Starting')
    address = ('localhost', 8080)
    server = socketserver.ThreadingTCPServer(address,
                                MyTCPHandler)
    print('Activating server')
    server.serve_forever() 
Example #18
Source File: peer.py    From py-blockchain-cli with MIT License 5 votes vote down vote up
def start(self):
        server = socketserver.ThreadingTCPServer(
            (self.host, self.port), _PeerRequestHandler)
        server.peer = self
        try:
            server.serve_forever()
        except KeyboardInterrupt as _:
            server.server_close() 
Example #19
Source File: test_socketserver.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_ThreadingTCPServer(self):
        self.run_server(socketserver.ThreadingTCPServer,
                        socketserver.StreamRequestHandler,
                        self.stream_examine) 
Example #20
Source File: proxy.py    From net.tcp-proxy with GNU General Public License v3.0 5 votes vote down vote up
def main():
    import argparse
    global trace_file, TARGET_HOST, TARGET_PORT

    HOST, PORT = "localhost", 8090

    parser = argparse.ArgumentParser()
    parser.add_argument('-t', '--trace_file', type=argparse.FileType('w'))
    parser.add_argument('-b', '--bind', default=HOST)
    parser.add_argument('-p', '--port', type=int, default=PORT)
    parser.add_argument('-n', '--negotiate', help='Negotiate with the given server name')
    parser.add_argument('TARGET_HOST')
    parser.add_argument('TARGET_PORT', type=int)

    args = parser.parse_args()

    TARGET_HOST = args.TARGET_HOST
    TARGET_PORT = args.TARGET_PORT

    trace_file = args.trace_file

    register_types()

    NETTCPProxy.negotiate = bool(args.negotiate)
    NETTCPProxy.server_name = args.negotiate

    if GSSAPIStream is None and NETTCPProxy.negotiate:
        log.error("GSSAPI not available, negotiation not possible. Try python2 with gssapi")
        sys.exit(1)

    server = SocketServer.ThreadingTCPServer((args.bind, args.port), NETTCPProxy)

    server.serve_forever() 
Example #21
Source File: ht_proxy_if.py    From hometop_HT3 with GNU General Public License v3.0 5 votes vote down vote up
def run(self):
        _ClientHandler.log_info("cht_proxy_daemon start as proxy-server:'{0}';port:'{1}'".format(self._ip_address, self._port_number))
        _ClientHandler.log_info("logfile:'{0}'".format(self._logfile))
        _serialdevice_initialised=[]

        for devicename in self.devicename_keys():
            if self.devicename_initflag(devicename) == 0:
                #check for already initialised serial device, if not then start transceiver_if
                serialdevice   = self.transceiver_serialdevice(devicename)
                if not serialdevice in (_serialdevice_initialised):
                    baudrate       = self.transceiver_baudrate(devicename)
                    devicetype     = self.transceiver_devicetype(devicename)
                    #start transceiver-if for that serial device
                    transceiver_if = cht_transceiver_if(serialdevice, baudrate, devicetype)
                    #add used serial-device to list
                    _serialdevice_initialised.append(serialdevice)
                    #add transceiver to list
                    self._ht_transceiver_if.append(transceiver_if)
                    transceiver_if.setDaemon(True)
                    transceiver_if.start()

                #set initialise-flag for devicename
                self.devicename_initflag(devicename, 1)



        try:
            self._server=socketserver.ThreadingTCPServer((self._ip_address, self._port_number), cht_RequestHandler)
            self._server.serve_forever()
            _ClientHandler.log_critical("cht_proxy_daemon terminated")
            _ClientHandler.log_info("---------------------------")
            raise
        except:
            _ClientHandler.log_critical("cht_proxy_daemon terminated")
            _ClientHandler.log_info("---------------------------")
            raise 
Example #22
Source File: v2rayMS_Server.py    From v2rayMS with MIT License 5 votes vote down vote up
def serve_listen():
    server = ThreadingTCPServer((HOST, PORT), Handler)
    server.serve_forever()
    print(server)


# 主函数 
Example #23
Source File: test_archive.py    From bob with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        super().setUp()
        self.httpd = socketserver.ThreadingTCPServer(("localhost", 0), createHttpHandler(self.repo.name))
        self.ip, self.port = self.httpd.server_address
        self.server = threading.Thread(target=self.httpd.serve_forever)
        self.server.daemon = True
        self.server.start() 
Example #24
Source File: server.py    From bc18-scaffold with MIT License 4 votes vote down vote up
def start_server(sock_file: str, game: Game, dockers, use_docker=True) -> socketserver.BaseServer:
    '''
    Start a socket server for the players to connect to
    Args:
        sock_file: This is a string name of the file that will be used for
                    as UnixStream

        game: The game information that is being run

        use_docker bool: whether to use docker or not

    Return:
        server_thread: The connection so it can be closed by parent functions at
                        the appropriate time
    '''

    # Create handler for mangaing each connections to server
    receive_handler = create_receive_handler(game, dockers, use_docker, True)

    if isinstance(sock_file, tuple):
        # tcp port
        server = socketserver.ThreadingTCPServer(sock_file, receive_handler)
    else:
        server = socketserver.ThreadingUnixStreamServer(sock_file, receive_handler)

    def wait_for_connections():
        time.sleep(BUILD_TIMEOUT)
        for player in game.players:
            if not player['built_successfully']:
                print('Player failed to connect to manager after',BUILD_TIMEOUT,'seconds:', player['player'])
                if bc.Team.Red == player['player'].team:
                    game.winner = 'player2'
                else:
                    game.winner = 'player1'
                game.disconnected = True
                game.game_over = True

    server_thread = threading.Thread(target=server.serve_forever, daemon=True)
    logging.info("Server Started at %s", sock_file)
    server_thread.start()
    waiter_thread = threading.Thread(target=wait_for_connections, daemon=True)
    waiter_thread.start()

    return server