在我的代理项目中,有时服务器进程(由教师给出)以错误(以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()
答案 0 :(得分:1)
使用return
是正确的方法(不过,在这之前你应该关闭连接)。
正如大卫所说的那样:
request = conn.recv(512)
可能是罪魁祸首。如果建立连接但没有发送数据,则主线程将被锁定。更不用说请求可能比512更大了。
在receivePage
函数中移动该行(并且不要将request
传递给Thread
构造函数)并告诉我们它是否有效。