在我的代理项目中,有时服务器进程(由老师给出)以错误(以 404 开头的字符串)结束,所以我希望发送请求的线程停止而不是继续。我尝试过使用“return”或“sys.exit()”,但这似乎阻止了一切,并且代理停止接收请求并创建线程。为什么?
from socket import *
from threading import *
import sys
import colors
import os
import time
def startPrefetch(pagesToPrefetch, mutex):
for i in pagesToPrefetch:
print i
def receivePage(conn, addr, request, mutex):
HOSTSERVER = "127.0.0.1"
SERVERPORT = 55555
socketRequestServer = socket(AF_INET, SOCK_STREAM)
socketRequestServer.connect((HOSTSERVER, SERVERPORT))
socketRequestServer.send(request)
finalResponse = ''
while True:
partialResponse = socketRequestServer.recv(64)
if (not partialResponse): break
finalResponse = finalResponse+partialResponse
if (finalResponse[0] == '4'):
c = colors.colors()
print c.ERROR + finalResponse + "INTERNAL SERVER ERROR"
print c.WHITE
return
#sys.exit(1)
socketRequestServer.close()
conn.sendall(finalResponse)
conn.close()
pagesToPrefetch = []
sourceToString = finalResponse.split(' ')
for i in sourceToString:
if (len(i) != 0):
if (i[0] == '<'):
pagesToPrefetch.append(i)
startPrefetch(pagesToPrefetch, mutex)
if __name__ == '__main__':
HOST = '127.0.0.1'
PORT = 55554
print 'Creating socket'
socketProxy = socket(AF_INET, SOCK_STREAM)
print 'bind()'
socketProxy.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
socketProxy.bind((HOST, PORT))
#Cache directory and mutex for it
mutex = Semaphore(1)
try:
os.mkdir("cache")
except OSError:
print 'Created cache directory'
while True:
print 'Waiting for connection request'
socketProxy.listen(1)
conn, addr = socketProxy.accept()
print 'Connected to ', addr
request = conn.recv(512)
receiver = Thread(target = receivePage, args = (conn, addr, request, mutex))
receiver.start()