本文整理汇总了Python中socketserver.ThreadingTCPServer.server_bind方法的典型用法代码示例。如果您正苦于以下问题:Python ThreadingTCPServer.server_bind方法的具体用法?Python ThreadingTCPServer.server_bind怎么用?Python ThreadingTCPServer.server_bind使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类socketserver.ThreadingTCPServer
的用法示例。
在下文中一共展示了ThreadingTCPServer.server_bind方法的4个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: WebUI
# 需要导入模块: from socketserver import ThreadingTCPServer [as 别名]
# 或者: from socketserver.ThreadingTCPServer import server_bind [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()
示例2: ThreadingServerInThread
# 需要导入模块: from socketserver import ThreadingTCPServer [as 别名]
# 或者: from socketserver.ThreadingTCPServer import server_bind [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()
示例3: WebUI
# 需要导入模块: from socketserver import ThreadingTCPServer [as 别名]
# 或者: from socketserver.ThreadingTCPServer import server_bind [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):
#.........这里部分代码省略.........
示例4: ModbusServer
# 需要导入模块: from socketserver import ThreadingTCPServer [as 别名]
# 或者: from socketserver.ThreadingTCPServer import server_bind [as 别名]
#.........这里部分代码省略.........
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()