【发布时间】:2010-10-11 11:41:54
【问题描述】:
这是我肮脏的小网络服务器:
class Serverhttp:
def __init__(self):
self.GET = re.compile("GET.*?HTTP")
self.POST = re.compile("POST.*?HTTP")
try :
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('localhost', 36000)
print >>sys.stderr, 'starting up on %s port %s' % server_address
sock.bind(server_address)
except :
time.sleep(2)
self.__init__()
# Listen for incoming connections
sock.listen(1)
off = 2
self.message = ""
while True:
# Wait for a connection
print >>sys.stderr, 'waiting for a connection'
if off == 2 or off == 1:
connection, client_address = sock.accept()
try:
print >>sys.stderr, 'connection from', client_address
# Receive the data in small chunks and retransmit it
while True:
data = connection.recv(1024)
print >>sys.stderr, 'received "%s"' % data
if data:
self.message = self.traitement(data)
connection.sendall(self.message)
connection.close()
connection, client_address = sock.accept()
else:
print >>sys.stderr, 'no more data from', client_address
break
finally:
# Clean up the connection
connection.close()
sock.close()
del(sock)
它或多或少地工作,但如果我退出服务器,端口仍然打开,我无法在同一个端口上重新连接。所以我正在寻找一种方法来杀死先例套接字或以一种好的方式退出。 问候和感谢
布西耶
【问题讨论】:
-
-1:当您可以使用库中已内置的
wsgiref或BaseHTTPServer时编写自己的。如果你不打算使用内置的HTTP服务器,请停止使用内置的socket库,直接使用/dev/eth驱动。
标签: python sockets kill shutdown