我正在运行一个简单的echo socketserver,每当连接一个客户端时,ctrl C都不会退出/终止服务器。相反它"挂起"直到客户端与套接字断开连接我已经读过某个地方,这是因为即使在主线程终止后仍有一个线程存活。我该如何解决这个问题?
Python代码(原谅一些缩进,它没有很好地复制粘贴):
import SocketServer
from SocketServer import TCPServer, ThreadingMixIn, StreamRequestHandler
import sys
import time
import socket
import os
class ThreadingTCPServer(ThreadingMixIn, TCPServer):
pass
class RequestHandler(StreamRequestHandler):
def handle(self):
print str(self.client_address) + 'connected'
data = "foo"
while data != "":
try:
data = self.rfile.readline().rstrip('\n')
except:
self.request.close()
print 'Socket Error'
break
print data
try:
self.wfile.write("OK\n")
except socket.error:
data = ""
print 'Handler Exiting'
self.request.close()
def finish(self):
print 'Client ' + str(self.client_address) + ' Disconnected'
if __name__ == '__main__':
PORT = 80
print 'Starting Server on port: ' + str(PORT)
ThreadingTCPServer.allow_reuse_address = True
server = ThreadingTCPServer(("", PORT), RequestHandler)
try:
server.serve_forever()
except KeyboardInterrupt:
print "\nServer Terminated"
server.shutdown()
sys.exit()
感谢所有回复,谢谢你的时间!
答案 0 :(得分:3)
尝试在程序开始时执行此操作:
import signal
signal.signal(signal.SIGINT, signal.SIG_DFL)
它的作用是恢复Ctrl-C(SIGINT)之前的默认值,即立即终止程序。