本文整理汇总了Python中socketserver.ThreadingTCPServer类的典型用法代码示例。如果您正苦于以下问题:Python ThreadingTCPServer类的具体用法?Python ThreadingTCPServer怎么用?Python ThreadingTCPServer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ThreadingTCPServer类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:bat-serjo,项目名称:vivisect,代码行数:60,代码来源:__init__.py
示例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)
开发者ID:agiacomolli,项目名称:tokenbus,代码行数:7,代码来源:busproxy.py
示例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()
开发者ID:LinkedModernismProject,项目名称:web_code,代码行数:7,代码来源:test_logging.py
示例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
开发者ID:LinkedModernismProject,项目名称:web_code,代码行数:7,代码来源:config.py
示例5: serve_forever
def serve_forever(self):
try:
ThreadingTCPServer.serve_forever(self)
except Exception as e:
if not self.run:
return
raise
开发者ID:bat-serjo,项目名称:vivisect,代码行数:10,代码来源:__init__.py
示例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
开发者ID:bat-serjo,项目名称:vivisect,代码行数:53,代码来源:http.py
示例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']
开发者ID:warstranger,项目名称:Simple-File-Server,代码行数:14,代码来源:sfserver.py
示例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()
开发者ID:Bitcoinsulting,项目名称:Bitcoin-WebUI,代码行数:29,代码来源:webui.py
示例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
开发者ID:Siuol,项目名称:pyModbusTCP,代码行数:32,代码来源:server.py
示例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
开发者ID:rayosborn,项目名称:nxpeaks,代码行数:16,代码来源:nxlogger.py
示例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()
开发者ID:sourceperl,项目名称:pyModbusTCP,代码行数:27,代码来源:server.py
示例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())
开发者ID:warstranger,项目名称:Simple-File-Server,代码行数:8,代码来源:sfserver.py
示例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()
开发者ID:Bitcoinsulting,项目名称:Bitcoin-WebUI,代码行数:11,代码来源:webui.py
示例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
开发者ID:ARudik,项目名称:ardulon-miner,代码行数:11,代码来源:webui.py
示例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()
开发者ID:XLSForm,项目名称:pyxform,代码行数:38,代码来源:server.py
示例16: listening
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))
开发者ID:weijingwei,项目名称:liwei_python,代码行数:16,代码来源:MainUI.py
示例17: MyRequestHandler
PORT = 12000
class MyRequestHandler(StreamRequestHandler):
def handle(self):
now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
conn = self.request
buf = conn.recv(1024)
if not buf:
print("{0}, connection from {1}, message: nothing".format(now, self.client_address))
else:
print("{0}, connection from {1}, message: {2}".format(now, self.client_address, buf))
server = ThreadingTCPServer(("127.0.0.1", PORT), MyRequestHandler)
print("listening on port", PORT)
server.serve_forever()
class ClientThread(threading.Thread):
def run(self):
for n in range(0, 60):
print("[{0}] Thread {1:03d}".format(self.getName(), random.randrange(1, 999)))
time.sleep(1)
th = []
for i in range(3):
th.append(ClientThread())
开发者ID:csddochi,项目名称:PythonHomework,代码行数:30,代码来源:hw26-4.py
示例18: __init__
def __init__(self,listen,prefix):
self.allow_reuse_address=True
ThreadingTCPServer.__init__(self,listen, TCPCauldronRequestHandler)
CauldronServer.__init__(self, prefix)
开发者ID:zbyufei,项目名称:ExtreMon,代码行数:4,代码来源:tcp_cauldron_server.py
示例19: ModbusServer
#.........这里部分代码省略.........
elif rx_bd_fc is const.WRITE_SINGLE_REGISTER:
(w_address, w_value) = struct.unpack('>HH', rx_body[1:])
if DataBank.set_words(w_address, [w_value]):
# send write ok frame
tx_body = struct.pack('>BHH', rx_bd_fc, w_address, w_value)
else:
exp_status = const.EXP_DATA_ADDRESS
# function Write Multiple Coils (0x0F)
elif rx_bd_fc is const.WRITE_MULTIPLE_COILS:
(b_address, b_count, byte_count) = struct.unpack('>HHB', rx_body[1:6])
# check quantity of updated coils
if (0x0001 <= b_count <= 0x07B0) and (byte_count >= (b_count/8)):
# allocate bits list
bits_l = [False] * b_count
# populate bits list with bits from rx frame
for i, item in enumerate(bits_l):
b_bit_pos = int(i/8)+6
b_bit_val = struct.unpack('B', rx_body[b_bit_pos:b_bit_pos+1])[0]
bits_l[i] = test_bit(b_bit_val, i % 8)
# write words to data bank
if DataBank.set_bits(b_address, bits_l):
# send write ok frame
tx_body = struct.pack('>BHH', rx_bd_fc, b_address, b_count)
else:
exp_status = const.EXP_DATA_ADDRESS
else:
exp_status = const.EXP_DATA_VALUE
# function Write Multiple Registers (0x10)
elif rx_bd_fc is const.WRITE_MULTIPLE_REGISTERS:
(w_address, w_count, byte_count) = struct.unpack('>HHB', rx_body[1:6])
# check quantity of updated words
if (0x0001 <= w_count <= 0x007B) and (byte_count == w_count * 2):
# allocate words list
words_l = [0] * w_count
# populate words list with words from rx frame
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=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
def start(self):
# bind and activate
self._service.server_bind()
self._service.server_activate()
# serve request
if self.no_block:
self._serve_th.start()
else:
self._service.serve_forever()
开发者ID:Siuol,项目名称:pyModbusTCP,代码行数:101,代码来源:server.py
示例20: _main
def _main():
host, port = socket.gethostname(), 1536
server = ThreadingTCPServer((host, port), TCPHandler)
server.serve_forever()
开发者ID:crvv,项目名称:weather,代码行数:4,代码来源:tcpserver.py
注:本文中的socketserver.ThreadingTCPServer类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论