首页 > 解决方案 > 使用多线程 python 服务器套接字未在浏览器中显示文件

问题描述

我遇到的问题如下:

我已经使用 Python 中的 socket 模块构建了一个多线程 TCP 服务器(或者至少,我尝试过)。服务器在其单线程实现中工作得很好,当我将它与我编写的客户端脚本一起使用时,似乎可以通过 CLI 很好地发送文件,但是当我将它与浏览器一起使用时,文件根本不显示 - HTTP 状态消息将通过(HTTP/1.0 200 OK 或 HTTP/1.0 404 File Not Found),但文件本身不会......或者如果有,它不会显示在浏览器中。

如果有人可以查看我的代码并帮助我弄清楚发生了什么,我将非常感激。这是我的代码的主要部分(我省略了 import 语句和 if dunder-name equals dunder-main 部分代码......):

#Thread function:

def threaded(connectionSocket):

    while True:

        try:
            #Request received from client
            message = connectionSocket.recv(1024)

            #Create received time stamp
            recv_time = time.time()

           #If the request is coming from the CLI, do this:
            filename = message

            #If the request is coming from a browser, do this:
            if len(message.decode('utf-8')) > 20:
                #Parse message from client
                filename = message.split()[1]

            filename = filename.decode('utf-8')
            f = open('.' + filename, 'r')
            outputdata = f.read(1024)

            #Send HTTP 200 OK Response message
            connectionSocket.sendall(bytes("HTTP/1.0 200 OK\n", "utf-8"))

            #Send data to client
            connectionSocket.sendall(outputdata.encode('utf-8'))

            #Display response to console
            print("HTTP/1.0 200 OK")

            #Create sent time stamp
            sent_time = time.time()
            break

        except:

            #Send response message for file not found
            connectionSocket.send(bytes('HTTP/1.0 404 File Not Found \n', 'utf-8'))

            #Display to console
            print("HTTP/1.0 404 File Not Found")

            #Create time stamp
            sent_time = time.time()
            break

    #Calculate RTT
    rtt = round((sent_time - recv_time), 3)

    #Display RTT
    print("RTT: " + str(rtt) + "ms")

    #Close connection and release lock
    connectionSocket.close()
    data_lock.release()
    print("Lock Released\n")

#The serve function which generates the server socket and initiates the thread

def serve():
    #Create a server socket
    serverSocket = socket(AF_INET, SOCK_STREAM)

    #Prepare a server socket
    HOST = '127.0.0.1'
    PORT = 50007
    serverSocket.bind((HOST, PORT))
    serverSocket.listen(5)

    while True:

        #Acquire lock
        data_lock.acquire()
        print("Lock acquired")
        print('Ready to serve...')

        #Establish the connection
        connectionSocket, addr = serverSocket.accept()
        print('Connected by ' + str(addr))

        #Start new thread
        start_new_thread(threaded, (connectionSocket,))
        break

    #Close this socket
    serverSocket.close()

#The main function:
def Main():
    while True:
        serve()

我觉得我可能遗漏了一些相当明显的东西,但我对套接字编程和多线程以及诸如此类的东西相当陌生。任何建议都会非常有帮助。

谢谢!

标签: pythonmultithreadingsockets

解决方案


推荐阅读