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


Python ThreadingTCPServer.shutdown方法代码示例

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


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

示例1: WebUI

# 需要导入模块: from socketserver import ThreadingTCPServer [as 别名]
# 或者: from socketserver.ThreadingTCPServer import shutdown [as 别名]
class WebUI(object):

  version = "Bitcoin WebUI v0.0.1"


  def __init__(self, config):
    self.config = config
    credentials = config.rpcusername + ":" + config.rpcpassword
    self.rpcauth = "Basic " + base64.b64encode(credentials.encode("utf_8")).decode("ascii")
    self.httpd = None


  def start(self):
    self.httpd = ThreadingTCPServer((self.config.bindip, self.config.bindport), RequestHandler, False)
    self.httpd.webui = self
    self.httpd.allow_reuse_address = True
    self.httpd.daemon_threads = True
    tcp_socket = socket.socket(self.httpd.address_family, self.httpd.socket_type)
    self.httpd.socket = ssl.wrap_socket(tcp_socket, self.config.privkeyfile, self.config.pubkeyfile, True)
    self.httpd.server_bind()
    self.httpd.server_activate()
    self.serverthread = Thread(None, self.httpd.serve_forever, "httpd")
    self.serverthread.start()


  def stop(self):
    self.httpd.shutdown()
    self.serverthread.join(5)
    self.httpd.server_close()
开发者ID:Bitcoinsulting,项目名称:Bitcoin-WebUI,代码行数:31,代码来源:webui.py

示例2: ThreadingServerInThread

# 需要导入模块: from socketserver import ThreadingTCPServer [as 别名]
# 或者: from socketserver.ThreadingTCPServer import shutdown [as 别名]
class ThreadingServerInThread(object):
    """
    Context manager for running a threading http server in a thread.

    Since the Thread is not using "daemon=True", it will keep Python running
    until the context manager exits, which means until request completion.
    """

    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
        )

    def _bind_and_activate(self):
        try:
            self.httpd.server_bind()
            self.httpd.server_activate()
        except Exception as e:
            self.httpd.server_close()
            raise e

    def start(self):
        self._bind_and_activate()
        thread = threading.Thread(target=self.httpd.serve_forever)
        thread.start()

    def stop(self):
        self.httpd.shutdown()
        self.httpd.server_close()

    def __enter__(self):
        self.start()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.stop()
开发者ID:XLSForm,项目名称:pyxform,代码行数:40,代码来源:server.py

示例3: LogRequestHandler

# 需要导入模块: from socketserver import ThreadingTCPServer [as 别名]
# 或者: from socketserver.ThreadingTCPServer import shutdown [as 别名]
# coding:utf-8
from socketserver import ThreadingTCPServer,StreamRequestHandler


class LogRequestHandler(StreamRequestHandler):
    def handle(self):
        print('client {} is online!'.format(self.client_address))
        filename = self.rfile.readline().decode().strip()
        fd = open('/logs/{0}'.format(filename),'a')
        while True:
            data = self.rfile.readline()
            if not data.strip():
                break
            fd.write(data.decode())
            fd.flush()
        print('close connection')
        fd.close()


if __name__ == '__main__':
    addr = ('192.168.2.53',8080)
    server = ThreadingTCPServer(addr,LogRequestHandler)
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        server.shutdown()
开发者ID:ChinaChou,项目名称:py2016,代码行数:28,代码来源:logServer.py

示例4: WebUI

# 需要导入模块: from socketserver import ThreadingTCPServer [as 别名]
# 或者: from socketserver.ThreadingTCPServer import shutdown [as 别名]
class WebUI(BaseFrontend):

    version = "theseven.webui v0.1.0"
    default_name = "WebUI"
    can_log = True
    can_configure = True
    can_autodetect = True
    settings = dict(
        BaseFrontend.settings,
        **{
            "port": {"title": "HTTP port", "type": "int", "position": 1000},
            "users": {
                "title": "Users",
                "type": "dict",
                "key": {"title": "User:Password", "type": "string"},
                "value": {
                    "title": "Privilege level",
                    "type": "enum",
                    "values": [
                        {"value": "readonly", "title": "Read only access"},
                        {"value": "admin", "title": "Full access"},
                    ],
                },
                "position": 2000,
            },
            "log_buffer_max_length": {"title": "Maximum log buffer length", "type": "int", "position": 3000},
            "log_buffer_purge_size": {"title": "Log buffer purge size", "type": "int", "position": 3010},
        }
    )

    @classmethod
    def autodetect(self, core):
        core.add_frontend(self(core))

    def __init__(self, core, state=None):
        super(WebUI, self).__init__(core, state)
        self.log_lock = RLock()

    def apply_settings(self):
        super(WebUI, self).apply_settings()
        if not "port" in self.settings:
            self.settings.port = 8832
        if not "users" in self.settings:
            self.settings.users = {"admin:mpbm": "admin"}
        if not "uiconfig" in self.settings:
            self.settings.uiconfig = {"loggadget": {"loglevel": self.core.default_loglevel}}
        if not "log_buffer_max_length" in self.settings:
            self.settings.log_buffer_max_length = 1000
        if not "log_buffer_purge_size" in self.settings:
            self.settings.log_buffer_purge_size = 100
        if self.started and self.settings.port != self.port:
            self.async_restart(3)

    def _reset(self):
        self.log_buffer = []
        self.log_listeners = []

    def _start(self):
        super(WebUI, self)._start()
        self.httpd = ThreadingTCPServer(("", self.settings.port), RequestHandler, False)
        self.httpd.webui = self
        self.httpd.allow_reuse_address = True
        self.httpd.daemon_threads = True
        self.httpd.server_bind()
        self.httpd.server_activate()
        self.serverthread = Thread(None, self.httpd.serve_forever, self.settings.name + "_httpd")
        self.serverthread.daemon = True
        self.serverthread.start()
        self.port = self.settings.port

    def _stop(self):
        self.httpd.shutdown()
        self.serverthread.join(10)
        self.httpd.server_close()
        super(WebUI, self)._stop()

    def write_log_message(self, source, timestamp, loglevel, messages):
        if not self.started:
            return
        data = {
            "timestamp": time.mktime(timestamp.timetuple()) * 1000 + timestamp.microsecond / 1000.0,
            "loglevel": loglevel,
            "source": source.settings.name,
            "message": [{"data": data, "format": format} for data, format in messages],
        }
        with self.log_lock:
            for queue in self.log_listeners:
                queue.put(data)
            self.log_buffer.append(data)
            if len(self.log_buffer) > self.settings.log_buffer_max_length:
                self.log_buffer = self.log_buffer[self.settings.log_buffer_purge_size :]

    def register_log_listener(self, listener):
        with self.log_lock:
            if not listener in self.log_listeners:
                self.log_listeners.append(listener)
            for data in self.log_buffer:
                listener.put(data)

    def unregister_log_listener(self, listener):
#.........这里部分代码省略.........
开发者ID:TheSeven,项目名称:Modular-Python-Bitcoin-Miner,代码行数:103,代码来源:webui.py

示例5: ModbusServer

# 需要导入模块: from socketserver import ThreadingTCPServer [as 别名]
# 或者: from socketserver.ThreadingTCPServer import shutdown [as 别名]

#.........这里部分代码省略.........
                        for i, item in enumerate(words_l):
                            w_offset = i * 2 + 6
                            words_l[i] = struct.unpack('>H', rx_body[w_offset:w_offset + 2])[0]
                        # write words to data bank
                        if DataBank.set_words(w_address, words_l):
                            # send write ok frame
                            tx_body = struct.pack('>BHH', rx_bd_fc, w_address, w_count)
                        else:
                            exp_status = const.EXP_DATA_ADDRESS
                    else:
                        exp_status = const.EXP_DATA_VALUE
                else:
                    exp_status = const.EXP_ILLEGAL_FUNCTION
                # check exception
                if exp_status != const.EXP_NONE:
                    # format body of frame with exception status
                    tx_body = struct.pack('BB', rx_bd_fc + 0x80, exp_status)
                # build frame header
                tx_head = struct.pack('>HHHB', rx_hd_tr_id, rx_hd_pr_id, len(tx_body) + 1, rx_hd_unit_id)
                # send frame
                self.request.send(tx_head + tx_body)
            self.request.close()

    def __init__(self, host='localhost', port=const.MODBUS_PORT, no_block=False, ipv6=False):
        """Constructor

        Modbus server constructor.

        :param host: hostname or IPv4/IPv6 address server address (optional)
        :type host: str
        :param port: TCP port number (optional)
        :type port: int
        :param no_block: set no block mode, in this mode start() return (optional)
        :type no_block: bool
        :param ipv6: use ipv6 stack
        :type ipv6: bool
        """
        # public
        self.host = host
        self.port = port
        self.no_block = no_block
        self.ipv6 = ipv6
        # private
        self._running = False
        self._service = None
        self._serve_th = None

    def start(self):
        """Start the server.

        Do nothing if server is already running.
        This function will block if no_block is not set to True.
        """
        if not self.is_run:
            # set class attribute
            ThreadingTCPServer.address_family = socket.AF_INET6 if self.ipv6 else socket.AF_INET
            ThreadingTCPServer.daemon_threads = True
            # init server
            self._service = ThreadingTCPServer((self.host, self.port), self.ModbusService, bind_and_activate=False)
            # set socket options
            self._service.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self._service.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
            # TODO test no_delay with bench
            self._service.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
            # bind and activate
            self._service.server_bind()
            self._service.server_activate()
            # serve request
            if self.no_block:
                self._serve_th = Thread(target=self._serve)
                self._serve_th.daemon = True
                self._serve_th.start()
            else:
                self._serve()

    def stop(self):
        """Stop the server.

        Do nothing if server is already not running.
        """
        if self.is_run:
            self._service.shutdown()
            self._service.server_close()

    @property
    def is_run(self):
        """Return True if server running.

        """
        return self._running

    def _serve(self):
        try:
            self._running = True
            self._service.serve_forever()
        except:
            self._service.server_close()
            raise
        finally:
            self._running = False
开发者ID:sourceperl,项目名称:pyModbusTCP,代码行数:104,代码来源:server.py

示例6: MainUI

# 需要导入模块: from socketserver import ThreadingTCPServer [as 别名]
# 或者: from socketserver.ThreadingTCPServer import shutdown [as 别名]
class MainUI(Ui_ASTM_Clent):
    def _del_(self):
        if hasattr(self, "server"):
            self.server.shutdown()
            self.server = None
            self.t._stop()
            
    def searchClicked(self):
        sid = self.txtSearch.text()
        result = OperationDB().selectTest((sid,))
        print(result)
        self.searchCallBack(result)
        
    def testConnClicked(self):
        sendIP = self.txtSendIP.text()
        sendPort = self.txtSendPort.text()
        try:
            TCPClient(sendIP, sendPort).send(("testConn", ()), self.testConnCallBack)
        except Exception as e:
            print(e)
            self.txtConsole.append(str(e))
        
    def testConnCallBack(self, params):
        print(params)
        if params == "success":
            print(params)
            self.txtConsole.append(params)
            
    def listening(self):
        if hasattr(self, "server"):
            self.server.shutdown()
            self.server = None
            self.t._stop()
        listenIP = self.txtLocalIP.text()
        listenPort = self.txtLocalPort.text()
        try:
            self.server = ThreadingTCPServer((listenIP, int(listenPort)), EchoRequestHandler)
            print("server running at", listenIP, listenPort)
            self.txtConsole.append("server running at " + listenIP + " " + listenPort)
            self.t = Thread(target=self.server.serve_forever)
            self.t.start()
        except Exception as e:
            print(e)
            self.txtConsole.append(str(e))
    
    def connClicked(self):
        sendIP = self.txtSendIP.text()
        sendPort = self.txtSendPort.text()
        try:
            TCPClient(sendIP, sendPort).send(("testConn", ()), self.connCallBack)
        except Exception as e:
            print(e)
            self.txtConsole.append(str(e))
        
    def connCallBack(self, params):
        print(params)
        if params == "success":
            self.sendIP = self.txtSendIP.text()
            self.sendPort = self.txtSendPort.text()
            self.txtConsole.append(self.sendIP + ":" + self.sendPort + " connected.")
        else:
            self.txtConsole.append(self.sendIP + ":" + self.sendPort + " connect failed.")
        
    def orderButClicked(self):
        sid = self.txt_sid.text()
        pid = self.txt_pid.text()
        pname = self.txt_pname.text()
        page = self.txt_page.text()
        pgender = self.txt_gender.text()
        status = self.txt_status.text()
        if sid == "":
            self.txtConsole.append("please type sid")
            return
        if pid == "":
            self.txtConsole.append("please type pid")
            return
        if pname == "":
            self.txtConsole.append("please type name")
            return
        if page == "":
            self.txtConsole.append("please type age")
            return
        if pgender == "":
            self.txtConsole.append("please type gender")
            return
        if status == "":
            self.txtConsole.append("please type status")
            return
        albchecked = self.chk_ALB.isChecked()
        altchecked = self.chk_ALT.isChecked()
        astchecked = self.chk_AST.isChecked()
        alpchecked = self.chk_ALP.isChecked()
        mgchecked = self.chk_MG.isChecked()
        ggtchecked = self.chk_GGT.isChecked()
        hcychecked = self.chk_HCY.isChecked()
        uricchecked = self.chk_URIC.isChecked()
        bunchecked = self.chk_BUN.isChecked()
        cholchecked = self.chk_CHOL.isChecked()
        sycschecked = self.chk_SYCS.isChecked()
        glucchecked = self.chk_GLUC.isChecked()
#.........这里部分代码省略.........
开发者ID:weijingwei,项目名称:liwei_python,代码行数:103,代码来源:MainUI.py

示例7: EchoHandler

# 需要导入模块: from socketserver import ThreadingTCPServer [as 别名]
# 或者: from socketserver.ThreadingTCPServer import shutdown [as 别名]
import sys
from socketserver import BaseRequestHandler, ThreadingTCPServer

class EchoHandler(BaseRequestHandler):

    def handle(self):
        print("Got connection from", self.client_address)
        while True:
            msg = self.request.recv(8192)
            if not msg:
                break
            print("Replying:", msg)
            self.request.send(msg)

if __name__ == '__main__':
    if len(sys.argv) < 2:
        print("Usage: python main.py port")
        sys.exit(1)
    port = int(sys.argv[1])
    try:
        serv = ThreadingTCPServer(('', port), EchoHandler)
        serv.serve_forever()
    except KeyboardInterrupt:
        serv.shutdown()
        serv.server_close()
开发者ID:lekum,项目名称:python-snippets,代码行数:27,代码来源:main.py


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