如何在Python中完全退出服務器?代碼如server.shutdown()
只是關閉傳入的請求。任何人都可以提出任何代碼完成退出服務器?這是一個簡單的socketserver。如何在python中完全退出服務器?
這是我的代碼服務器:
#!/usr/bin/python
import socket
from threading import Thread
class sockServer:
def __init__(self,port):
self.socket= socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.socket.bind(port)
self.socket.listen(5)
def _run(self):
while True:
request, client_address =self.socket.accept()
counter=self.req_thread(self,request)
counter.start()
class req_thread(Thread):
def __init__(self,controller,request):
Thread.__init__(self)
self.controller=controller
self.request=request
self.setDaemon(True)
def run(self):
input=self.request.makefile('rb',0)
output=self.request.makefile('wb',0)
l=True
i=0
try:
while l:
l=input.readline()
if l!="exit\r\n":
print "x"
output.write(bytes('hello\n'))
else:
print "y"
self.request.shutdown(2)
run=False
except socket.error:
pass
if __name__ == '__main__':
import sys
if len(sys.argv) < 3:
print('Usage: %s [hostname] [port number]' % sys.argv[0])
sys.exit(1)
hostname = sys.argv[1]
port = int(sys.argv[2])
global run
run=True
while run:
server=sockServer((hostname,port))
server._run()
使用可變run
的方法是沒有好處!
修復代碼的格式 –
sys.exit(0)??? –