2015-04-27 64 views
0

我想在python中創建一個多線程服務器,它現在發送一個標題行,然後請求html文件,但是我遇到了一點障礙。我很確定我的線程在函數完成時不會退出。我的服務器正在打印「準備投放......」的次數超過應有的次數(並且偶爾遇到隨機錯誤)。我聽說如果一個線程遇到一個處理的異常,它可能不會退出,但即使事情順利運行,它似乎也不會退出。在python多線程服務器中退出線程

我對python很陌生,習慣於在C中創建這些內容,我可以簡單地從線程中退出線程,但是我的研究告訴我在python中並不那麼簡單。任何關於如何修復或改善服務器的幫助都會很棒!

#import socket module 
from socket import * 
import threading 

def work(connectionSocket): 
    try: 
     message = connectionSocket.recv(1024) 
     filename = message.split()[1] 
     f = open(filename[1:]) 
     outputdata = f.read() 
     #Send one HTTP header line into socket 
     connectionSocket.send("Header Line") 

     #Send the content of the requested file to the client 
     for i in range(0, len(outputdata)): 
      connectionSocket.send(outputdata[i]) 
     connectionSocket.close() 
    except IOError: 
     #Send response message for file not found 
     connectionSocket.send("404 File Not Found.") 
     connectionSocket.close() 

    return 

def server(): 
    threads = [] 
    serverPort = 14009 
    serverSocket = socket(AF_INET, SOCK_STREAM) 
    #Prepare a sever socket 
    serverSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) 
    serverSocket.bind(('', serverPort)) 
    serverSocket.listen(1) 
    while True: 
     #Establish the connection 
     print 'Ready to serve...' 
     connectionSocket, addr = serverSocket.accept() 
     t = threading.Thread(target=work, args=(connectionSocket,)) 
     threads.append(t) 
     t.start() 

    serverSocket.close() 

if __name__ == '__main__': 
    server() 

回答

0

它打印出「準備服務器」不止一次的原因是,你把print 'Ready to serve...'的循環。如果您只希望打印一次,請將其放在循環之外。

爲了確保每個線程退出,在程序結束時加入所有線程是一種更好的做法。那麼代碼將是這樣的:

print('Ready to serve...') 
while True: 
    #Establish the connection 
    try: 
     connectionSocket, addr = serverSocket.accept() 
    except KeyboardInterrupt: 
     break 
    t = threading.Thread(target=work, args=(connectionSocket,)) 
    threads.append(t) 
    t.start() 

print("Exiting") 
for t in threads: 
    t.join(5) 
serverSocket.close() 
+0

謝謝!我知道我已經在循環中「準備好服務......」,但我期望它能夠按照每個請求再次打印一次,但是在每次請求之後打印兩次或更多,這導致我相信該線程不會退出並返回到循環主線程已經在哪裏,並與它同時循環。 – boxofun1

+0

隨着你的代碼,我絕對不會再有任何錯誤,但它仍然打印準備好每次請求多次服務......再次,謝謝你! – boxofun1