0

在我的代理项目中,有时服务器进程(由老师给出)以错误(以 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()
4

1 回答 1

1

使用return是正确的方法(不过,您应该在这样做之前关闭连接)。

正如大卫建议的那样:

request = conn.recv(512)

可能是罪魁祸首。如果建立连接但没有发送数据,则主线程将被锁定。更不用说请求可能大于 512。

将该行移到函数内部receivePage(并且不要传递requestThread构造函数)并让我们知道它是否有效。

于 2013-02-15T12:30:18.813 回答