本文整理汇总了Python中SocketServer.ThreadingTCPServer.server_close方法的典型用法代码示例。如果您正苦于以下问题:Python ThreadingTCPServer.server_close方法的具体用法?Python ThreadingTCPServer.server_close怎么用?Python ThreadingTCPServer.server_close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类SocketServer.ThreadingTCPServer
的用法示例。
在下文中一共展示了ThreadingTCPServer.server_close方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: FileSearchServer
# 需要导入模块: from SocketServer import ThreadingTCPServer [as 别名]
# 或者: from SocketServer.ThreadingTCPServer import server_close [as 别名]
class FileSearchServer(Thread):
""" Thread which answers to file/tag queries sent through unix socket. """
def __init__(self, pname='SET_ME_PLEASE'):
Thread.__init__(self)
self.name = "%s/%s" % (
pname, str(self.__class__).rsplit('.', 1)[1].split("'")[0])
# old socket from a crashed daemon ?
# remove it, the ThreadingUnixStreamServer will create it.
#if os.path.exists(socket_path): os.unlink(socket_path)
self._stop_event = Event()
self.server = ThreadingTCPServer(('127.0.0.1', searcher_port), FileSearchRequestHandler)
self.server.allow_reuse_address = True
# TODO: the socket is set to non-blocking to be able to gracefully terminate the thread,
# but this could lead to CPU hogging problems. VERIFY THIS !!
self.server.socket.setblocking(False)
def run(self):
logging.progress("%s: thread running." % (self.getName()))
#os.chmod(socket_path, stat.S_IRUSR|stat.S_IWUSR|stat.S_IRGRP|stat.S_IWGRP|stat.S_IROTH|stat.S_IWOTH)
while not self._stop_event.isSet():
self.server.handle_request()
time.sleep(0.01)
logging.progress("%s: thread ended." % (self.getName()))
def stop(self):
if not self._stop_event.isSet():
logging.progress("%s: stopping thread." % (self.getName()))
self._stop_event.set()
self.server.socket.close()
self.server.server_close()
if os.path.exists(socket_path):
os.unlink(socket_path)
示例2: Server
# 需要导入模块: from SocketServer import ThreadingTCPServer [as 别名]
# 或者: from SocketServer.ThreadingTCPServer import server_close [as 别名]
class Server(Thread):
def __init__(self, host="127.0.0.1", port=3794, handler=Handler):
Thread.__init__(self)
self.server = ThreadingTCPServer((host, port), handler)
def run(self):
self.server.serve_forever()
def stopRunning(self):
self.server.shutdown()
self.server.server_close()
示例3: main
# 需要导入模块: from SocketServer import ThreadingTCPServer [as 别名]
# 或者: from SocketServer.ThreadingTCPServer import server_close [as 别名]
def main():
global world
world = World()
z = ThreadingTCPServer(('', 4000), MudHandler)
try: z.serve_forever()
except KeyboardInterrupt:
world.global_message('World is shutting down')
for plr in world.players_at_location(None):
try: plr.parse('quit')
except: print 'ERROR: %s could not quit gracefully' % plr.name
z.server_close()
world.save()
示例4: ALPSTCPServer
# 需要导入模块: from SocketServer import ThreadingTCPServer [as 别名]
# 或者: from SocketServer.ThreadingTCPServer import server_close [as 别名]
class ALPSTCPServer():
bufsize = 1500
@property
def connections_list(self):
return self.connections.keys()
def __init__(self, ip, port, receiver_func=None, connection_event_func=None, background=False, thread_name="TCPServer Thread"):
self.ip_string = ip
self.port = port
self.receiver_func_callback = receiver_func
self.connection_event_callback = connection_event_func
self.background = background
self.connections = {}
self.tcpserver = ThreadingTCPServer((self.ip_string, self.port), self.__request_handle_process)
self.tcpserver.allow_reuse_address = True
tcpsock_thread = ALPSThread(threadfunc=self.tcpserver.serve_forever, threadname=thread_name)
tcpsock_thread.setDaemon(not self.background)
tcpsock_thread.start()
def __request_handle_process(self, sock_obj, client_address, server):
self.connections[client_address] = sock_obj
if callable(self.connection_event_callback):
self.connection_event_callback(self, client_address, True)
while True:
try:
data = sock_obj.recv(self.bufsize)
except:
data = ''
if data:
if callable(self.receiver_func_callback):
self.receiver_func_callback(self, client_address, data)
# print client_address
else:
self.connections.pop(client_address)
if callable(self.connection_event_callback):
self.connection_event_callback(self, client_address, False)
break
def server_close(self):
for sock_obj in self.connections.values():
self.tcpserver.shutdown_request(sock_obj)
self.tcpserver.shutdown()
self.tcpserver.server_close()
def send(self, client_address, message, error_except=True):
if client_address not in self.connections.keys():
ALPSDebug.alps_error('socket not exist error')
return False
connection = self.connections[client_address]
if not error_except:
return connection.sendall(message)
try:
connection.sendall(message)
except Exception as e:
ALPSDebug.alps_error(e, '\n', inspect.getframeinfo((inspect.currentframe().f_back)))
return False
return True
def send_to_all_connections(self, message, error_except=True):
if len(self.connections) == 0:
return True
for sock_obj in self.connections.values():
if error_except:
try:
sock_obj.sendall(message)
except Exception as e:
ALPSDebug.alps_error(e, '\n', inspect.getframeinfo((inspect.currentframe().f_back)))
return False
else:
sock_obj.sendall(message)
return True
示例5: PySAPNIStreamSocketTest
# 需要导入模块: from SocketServer import ThreadingTCPServer [as 别名]
# 或者: from SocketServer.ThreadingTCPServer import server_close [as 别名]
class PySAPNIStreamSocketTest(unittest.TestCase):
test_port = 8005
test_address = "127.0.0.1"
test_string = "TEST" * 10
def start_server(self, handler_cls):
self.server = ThreadingTCPServer((self.test_address, self.test_port),
handler_cls,
bind_and_activate=False)
self.server.allow_reuse_address = True
self.server.server_bind()
self.server.server_activate()
self.server_thread = Thread(target=self.server.serve_forever)
self.server_thread.start()
def stop_server(self):
self.server.shutdown()
self.server.server_close()
self.server_thread.join()
def test_sapnistreamsocket(self):
"""Test SAPNIStreamSocket"""
self.start_server(SAPNITestHandler)
sock = socket.socket()
sock.connect((self.test_address, self.test_port))
self.client = SAPNIStreamSocket(sock)
packet = self.client.sr(self.test_string)
packet.decode_payload_as(Raw)
self.client.close()
self.assertIn(SAPNI, packet)
self.assertEqual(packet[SAPNI].length, len(self.test_string))
self.assertEqual(packet.payload.load, self.test_string)
self.stop_server()
def test_sapnistreamsocket_base_cls(self):
"""Test SAPNIStreamSocket handling of custom base packet classes"""
self.start_server(SAPNITestHandler)
class SomeClass(Packet):
fields_desc = [StrField("text", None)]
sock = socket.socket()
sock.connect((self.test_address, self.test_port))
self.client = SAPNIStreamSocket(sock, base_cls=SomeClass)
packet = self.client.sr(self.test_string)
self.client.close()
self.assertIn(SAPNI, packet)
self.assertIn(SomeClass, packet)
self.assertEqual(packet[SAPNI].length, len(self.test_string))
self.assertEqual(packet[SomeClass].text, self.test_string)
self.stop_server()
def test_sapnistreamsocket_getnisocket(self):
"""Test SAPNIStreamSocket get nisocket class method"""
self.start_server(SAPNITestHandler)
self.client = SAPNIStreamSocket.get_nisocket(self.test_address,
self.test_port)
packet = self.client.sr(self.test_string)
packet.decode_payload_as(Raw)
self.client.close()
self.assertIn(SAPNI, packet)
self.assertEqual(packet[SAPNI].length, len(self.test_string))
self.assertEqual(packet.payload.load, self.test_string)
self.stop_server()
def test_sapnistreamsocket_without_keep_alive(self):
"""Test SAPNIStreamSocket without keep alive"""
self.start_server(SAPNITestHandlerKeepAlive)
sock = socket.socket()
sock.connect((self.test_address, self.test_port))
self.client = SAPNIStreamSocket(sock, keep_alive=False)
packet = self.client.sr(self.test_string)
packet.decode_payload_as(Raw)
self.client.close()
# We should receive a PING instead of our packet
self.assertIn(SAPNI, packet)
self.assertEqual(packet[SAPNI].length, len(SAPNI.SAPNI_PING))
self.assertEqual(packet.payload.load, SAPNI.SAPNI_PING)
self.stop_server()
def test_sapnistreamsocket_with_keep_alive(self):
"""Test SAPNIStreamSocket with keep alive"""
self.start_server(SAPNITestHandlerKeepAlive)
#.........这里部分代码省略.........
示例6: LoggerServer
# 需要导入模块: from SocketServer import ThreadingTCPServer [as 别名]
# 或者: from SocketServer.ThreadingTCPServer import server_close [as 别名]
class LoggerServer(threading.Thread):
def __init__(self):
super(LoggerServer, self).__init__()
self.server = None
self.mh = None
self.omh = None
def run(self):
# check logger path
logger_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), constants.LOGGER_DIR)
logger_online_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), constants.LOGGER_ONLINE_DIR)
if os.path.exists(logger_path):
if not os.path.isdir(logger_path):
os.remove(logger_path)
os.mkdir(logger_path)
else:
os.mkdir(logger_path)
logger_file = os.path.join(logger_path, constants.LOGGER_FILE)
logger_online_file = os.path.join(logger_online_path, constants.LOGGER_ONLINE_FILE)
# rotating file handler
#rh = logging.handlers.RotatingFileHandler(logger_file,
# maxBytes = constants.LOGGER_FILE_MAX_BYTE,
# backupCount = constants.LOGGER_FILE_BACKUP_COUNT)
#rh.setLevel(logging.DEBUG)
# RotatingFileHandler failed sometimes because of os.rename(), so change to FileHandler, and maintain the log files manually
if os.path.exists(logger_file):
logger_file_stat = os.stat(logger_file)
if logger_file_stat.st_size > constants.LOGGER_FILE_MAX_BYTE:
file_list = os.listdir(logger_path)
for count in range(constants.LOGGER_FILE_BACKUP_COUNT, 0, -1):
if os.path.exists('%s.%s' % (logger_file, count)):
if count == constants.LOGGER_FILE_BACKUP_COUNT:
os.remove('%s.%s' % (logger_file, count))
else:
os.rename('%s.%s' % (logger_file, count), '%s.%s' % (logger_file, count + 1))
os.rename(logger_file, '%s.%s' % (logger_file, str(1)))
fh = logging.FileHandler(logger_file)
fh.setLevel(logging.DEBUG)
ofh = logging.FileHandler(logger_online_file)
ofh.setLevel(logging.DEBUG)
# memory handler for rotate file handler
self.mh = logging.handlers.MemoryHandler(constants.LOGGER_FILE_MEMORY_CACHE, target = fh)
self.mh.setLevel(logging.DEBUG)
self.omh = logging.handlers.MemoryHandler(constants.LOGGER_FILE_MEMORY_CACHE, target = ofh)
self.omh.setLevel(logging.DEBUG)
# set logger format
formatter = logging.Formatter("%(asctime)s - %(name)s - %(filename)s[line:%(lineno)d] - %(levelname)s - %(message)s")
#rh.setFormatter(formatter)
fh.setFormatter(formatter)
ofh.setFormatter(formatter)
self.mh.setFormatter(formatter)
self.omh.setFormatter(formatter)
# main logger
logger = logging.getLogger(constants.LOGGER_SERVER_NAME)
logger.propagate = 0
logger.setLevel(logging.DEBUG)
# add handle to logger
logger.addHandler(self.mh)
logger.addHandler(self.omh)
self.server = ThreadingTCPServer((constants.LOGGER_SERVER_IP, constants.LOGGER_SERVER_PORT), LogRequestHandler)
self.server.serve_forever()
self.server.server_close()
def stop_server(self):
if self.mh:
self.mh.flush()
if self.omh:
self.omh.flush()
if self.server:
self.server.shutdown()
def get_server(self):
return self.server
示例7: sayhello
# 需要导入模块: from SocketServer import ThreadingTCPServer [as 别名]
# 或者: from SocketServer.ThreadingTCPServer import server_close [as 别名]
def sayhello(self):
print "hello"
self.wfile.write("hello")
global t #Notice: use global variable!
t = threading.Timer(2.0, self.sayhello)
t.start()
def get_gps():
print "-----gps"
return "lat,lat"
if __name__ == "__main__":
host = "" # 主机名,可以是ip,像localhost的主机名,或""
port = 9999 # 端口
addr = (host, port)
try:
pwm = PiPWM()
# ThreadingTCPServer从ThreadingMixIn和TCPServer继承
#class ThreadingTCPServer(ThreadingMixIn, TCPServer): pass
server = ThreadingTCPServer(addr, MyStreamRequestHandlerr)
server.serve_forever()
except KeyboardInterrupt:
pass
server.server_close()
pwm.stop()
示例8: usage
# 需要导入模块: from SocketServer import ThreadingTCPServer [as 别名]
# 或者: from SocketServer.ThreadingTCPServer import server_close [as 别名]
hostaddr = "127.0.0.1"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect(("google.com",80))
hostaddr = s.getsockname()[0]
s.close()
except:
print "google.com is unreachable. Are you connectec to internet?"
print "Using %s (localhost)" % hostaddr
return hostaddr
def usage():
print "usage:\n\t./srv_init.py <port #>"
if __name__ == "__main__":
if len(sys.argv) != 2:
print "Incorrect number of parameters!"
usage()
sys.exit()
server_addr = (getMyIP(), int(sys.argv[1])) # The first parameter is the port
print "Listening to connections on " + str(server_addr) + " address."
s = ThreadingTCPServer(server_addr, Handler)
try:
s.serve_forever()
except KeyboardInterrupt:
import sys
print "Exiting..."
s.server_close()
sys.exit(0)
示例9: server_close
# 需要导入模块: from SocketServer import ThreadingTCPServer [as 别名]
# 或者: from SocketServer.ThreadingTCPServer import server_close [as 别名]
def server_close(self):
ThreadingTCPServer.server_close(self)
os.unlink(self.server_address)
示例10: HttpMonitor
# 需要导入模块: from SocketServer import ThreadingTCPServer [as 别名]
# 或者: from SocketServer.ThreadingTCPServer import server_close [as 别名]
class HttpMonitor(Monitor):
"""
Monitor incoming documents on a HTTP endpoint.
For messages received via HTTP GET it uses the the path from URL path after host address as a 'str' type input.
For messages received via HTTP POST it expects the content body to be JSON.
Sockets:
output (*) : Document received on the HTTP endpoint.
Config:
host = "localhost"
port = 4000
max_length = 1024*1024 : Max length of incoming data via POST, in bytes.
"""
ThreadingTCPServer.allow_reuse_address = True # OBS: Class level setting.
def __init__(self, hook=None, **kwargs):
super(HttpMonitor, self).__init__(**kwargs)
self.output = self.create_socket("output", None, "Document received on the HTTP endpoint.")
self.config.set_default(host="localhost", port=4000)
self.config.set_default(
host = "localhost",
port = 4000,
max_length = 1024*1024 # 1 MB
)
self.hook = hook
def on_open(self):
self.log.info("Starting HTTP listener on %s:%d" % (self.config.host, self.config.port))
self._server = ThreadingTCPServer((self.config.host, self.config.port), _ServerHandlerClass, bind_and_activate=True)
self._server.owner = self
self._server.timeout = 1.0 # Max 1 second blocking in _server.handle_request()
def on_close(self):
self.log.info("Closing HTTP listener.")
self._server.server_close()
self._server = None
def _incoming_WITH_DATA(self, request_handler, verb, path, data):
if self.suspended:
return "Server suspended; incoming data ignored."
if verb == "GET":
self.total += 1
self.count += 1
# For GET, use path as document
if self.output.has_output:
self.output.send(path[1:])
data_obj = None
if data:
if request_handler.headers.gettype() == "application/json":
try:
data_obj = json.loads(data)
except Exception as e:
self.doclog.error("Failed to parse incoming data as JSON: " + e.message)
return "Failed to parse data as JSON."
else:
data_obj = data
if verb != "GET":
self.total += 1
self.count += 1
if self.output.has_output:
# For non-GET, use data as document
self.output.send(data_obj)
return self._call_hook(request_handler, verb, path, data_obj)
def _call_hook(self, request_handler, http_verb, path, data):
if self.hook:
try:
return self.hook(request_handler, http_verb, path, data)
except Exception as e:
self.log.exception("Failed to call hook: %s: %s" % (e.__class__.__name__, e))
def on_startup(self):
self.total = 0
self.count = 0
def on_tick(self):
self._server.handle_request()