Python:关闭先前的Python程序已经打开的套接字或关闭套接字的肮脏技巧
这是我肮脏的小网络服务器:
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)
它或多或少可以工作,但如果我退出服务器,端口仍然打开,我无法在同一端口上重新连接。所以我正在寻找一种方法来终止先前的套接字或以一种好的方式退出。 问候和感
谢布西埃
here is my dirty little web server :
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)
it works more or less but if i quit the server the port is still open and i can't reconnect on the same port. So i'am looking for a way to kill precedent socket or to exit in a nice way.
Regards and thanks
Bussiere
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
应该可以解决问题。
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
Should do the trick.