本文整理汇总了Python中socketserver.ThreadingTCPServer类的典型用法代码示例。如果您正苦于以下问题:Python ThreadingTCPServer类的具体用法?Python ThreadingTCPServer怎么用?Python ThreadingTCPServer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ThreadingTCPServer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
def __init__(self, host="", port=COBRA_PORT, sslcrt=None, sslkey=None, sslca=None, msgpack=False, json=False):
'''
Construct a cobra daemon object.
Parameters:
host - Optional hostname/ip to bind the service to (default: inaddr_any)
port - The port to bind (Default: COBRA_PORT)
msgpack - Use msgpack serialization
# SSL Options
sslcrt / sslkey - Specify sslcrt and sslkey to enable SSL server side
sslca - Specify an SSL CA key to use validating client certs
'''
self.thr = None
self.run = True
self.shared = {}
self.dowith = {}
self.host = host
self.port = port
self.reflock = RLock()
self.refcnts = {}
self.authmod = None
self.sflags = 0
if msgpack and json:
raise Exception('CobraDaemon can not use both msgpack *and* json!')
if msgpack:
requireMsgpack()
self.sflags |= SFLAG_MSGPACK
if json:
self.sflags |= SFLAG_JSON
# SSL Options
self.sslca = sslca
self.sslcrt = sslcrt
self.sslkey = sslkey
self.cansetattr = True
self.cangetattr = True
if sslcrt and not os.path.isfile(sslcrt):
raise Exception('CobraDaemon: sslcrt param must be a file!')
if sslkey and not os.path.isfile(sslkey):
raise Exception('CobraDaemon: sslkey param must be a file!')
if sslca and not os.path.isfile(sslca):
raise Exception('CobraDaemon: sslca param must be a file!')
self.allow_reuse_address = True
ThreadingTCPServer.__init__(self, (host, port), CobraRequestHandler)
if port == 0:
self.port = self.socket.getsockname()[1]
self.daemon_threads = True
self.recvtimeout = None
示例2: process_request
def process_request(self, request, client_address):
# Processa uma nova requisicao. Adiciona o novo cliente na lista de clientes
# mantida pelo servidor e chama o mesmo metodo da classe-base.
print("Novo cliente conectado " + request.getpeername()[0])
self.clients.append(request)
ThreadingTCPServer.process_request(self, request,
client_address)
示例3: __init__
def __init__(self, host='localhost',
port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
handler=LogRecordStreamHandler):
ThreadingTCPServer.__init__(self, (host, port), handler)
self.abort = False
self.timeout = 0.1
self.finished = threading.Event()
示例4: __init__
def __init__(self, host='localhost', port=DEFAULT_LOGGING_CONFIG_PORT,
handler=None):
ThreadingTCPServer.__init__(self, (host, port), handler)
logging._acquireLock()
self.abort = 0
logging._releaseLock()
self.timeout = 1
示例5: serve_forever
def serve_forever(self):
try:
ThreadingTCPServer.serve_forever(self)
except Exception as e:
if not self.run:
return
raise
示例6: __init__
def __init__(self, host="", port=COBRA_PORT, sslcrt=None, sslkey=None, sslca=None, sess_timeout=24, attr=True):
'''
Construct a cobra daemon object.
Parameters:
host - Optional hostname/ip to bind the service to (default: inaddr_any)
port - The port to bind (Default: COBRA_PORT)
timeout - The length any session can last, before forcing reconnect
attr - Toggle to turn off the ability to set or get attributes
# SSL Options
sslcrt / sslkey - Specify sslcrt and sslkey to enable SSL server side
sslca - Specify an SSL CA key to use validating client certs
'''
self.shared = {}
self.host = host
self.port = port
self.reflock = RLock()
self.refcnts = {}
self.authmod = None
self.attr = attr
self.sessions = {} # authenticated sessions
self.sess_timeout=sess_timeout*60
# SSL Options
self.sslca = sslca
self.sslcrt = sslcrt
self.sslkey = sslkey
if sslcrt and not os.path.isfile(sslcrt):
raise Exception('CobraDaemon: sslcrt param must be a file!')
if sslkey and not os.path.isfile(sslkey):
raise Exception('CobraDaemon: sslkey param must be a file!')
if sslca and not os.path.isfile(sslca):
raise Exception('CobraDaemon: sslca param must be a file!')
#ThreadingTCPServer.__init__(self, (host, port), CobraHttpConnectionHandler)
ThreadingTCPServer.__init__(self, (host, port), CobraHttpRequestHandler)
t = Thread(target=self._timeoutSessions)
t.setDaemon(1)
t.start()
if port == 0:
self.port = self.socket.getsockname()[1]
self.daemon_threads = True
self.recvtimeout = None
示例7: __init__
def __init__(self, config, handler_class):
server_address = (config['server']['ip'], config['server']['port'],)
# Bind and activate server in I{activate} method
ThreadingTCPServer.__init__(self, server_address, handler_class, 0)
Daemon.__init__(self, config['server']['pid'])
# Signals not catched in serve_forever, we need to execute serve_forever
# again because signals are raised exception in I{main} method
self.__by_signal_do = 0
self.__local_sock = None
self.allow_reuse_address = 1
self._config = config.copy()
self._aliases = {}
self.timeout = config['server']['timeout']
示例8: WebUI
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()
示例9: __init__
def __init__(self, host='localhost', port=502, 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
"""
self.host = host
self.port = port
self.no_block = no_block
self.ipv6 = ipv6
# 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)
# add thread for no block mode
if self.no_block:
self._serve_th = Thread(target=self._service.serve_forever)
self._serve_th.daemon = True
示例10: run
def run(self):
ThreadingTCPServer.__init__(self, (self.host, self.port), self.handler)
self.abort = 0
self.timeout = 1
self.logname = None
import select
abort = 0
while not abort:
rd, wr, ex = select.select([self.socket.fileno()],
[], [],
self.timeout)
if rd:
self.handle_request()
abort = self.abort
示例11: start
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()
示例12: finish_request
def finish_request(self, request, client_address):
try:
return ThreadingTCPServer.finish_request(self, request,
client_address)
except Exception as e:
from traceback import format_exception
i = sys.exc_info()
logging.error('\n'.join(format_exception(i[0], i[1], i[2])).strip())
示例13: start
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()
示例14: _start
def _start(self):
super(WebUI, self)._start()
self.httpd = ThreadingTCPServer(("", self.settings.port), RequestHandler, False)
self.httpd.webui = self
self.httpd.allow_reuse_address = 1
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
示例15: ThreadingServerInThread
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()