Python Web服务器套接字

时间:2016-10-29 15:20:25

标签: python sockets tcp server webserver

我必须用Python创建一个Web服务器。以下是我正在处理的代码。当我执行它时,我最初没有错误,它打印"准备服务.." ,但在打开浏览器并运行http://10.1.10.187:50997/HelloWorld.html(HelloWorld是与我的python代码在同一文件夹中的html文件,而10.1.10.187是我的IP地址和50997)是服务器端口之后,我得到一个TypeError说'像对象这样的字节是必需的,而不是str"。请帮我解决这个问题,如果需要进行任何其他修改,请告诉我。

    #Import socket module
    from socket import *

    #Create a TCP server socket
    #(AF_INET is used for IPv4 protocols)
    #(SOCK_STREAM is used for TCP)

    # Assign a port number
    serverPort = 50997

    serverSocket = socket(AF_INET, SOCK_STREAM)

    #serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)      

    #print ("hostname is: "), gethostname()
    #print ("hostname is: "), socket.gethostname()                          

    # Bind the socket to server address and server port
    serverSocket.bind(("", serverPort))

    # Listen to at most 1 connection at a time
    serverSocket.listen(1)

    # Server should be up and running and listening to the incoming    connections
    while True:
    print ("Ready to serve...")

        # Set up a new connection from the client
        connectionSocket, addr = serverSocket.accept()

        try:
            # Receives the request message from the client
            message =  connectionSocket.recv(1024)
            print ("Message is: "), message

            filename = message.split()[1]
            print ("File name is: "), filename

            f = open(filename[1:])

            outputdata = f.read()
            connectionSocket.send("HTTP/1.1 200 OK\r\n\r\n")

    for i in range(0, len(outputdata)):  
        connectionSocket.send(outputdata[i])
    connectionSocket.send("\r\n")

    # Close the client connection socket
    connectionSocket.close()

except IOError:
    # Send HTTP response message for file not found
    connectionSocket.send("HTTP/1.1 404 Not Found\r\n\r\n")
    connectionSocket.send("<html><head></head><body><h1>404 Not Found</h1></body></html>\r\n")
    # Close the client connection socket
    connectionSocket.close()

    serverSocket.close() 

我正在冒犯的错误 -

    Ready to serve...
    Message is: 
    File name is: 
    Traceback (most recent call last):
    File "intro.py", line 56, in <module>
    connectionSocket.send("HTTP/1.1 200 OK\r\n\r\n")
    TypeError: a bytes-like object is required, not 'str'

1 个答案:

答案 0 :(得分:1)

您需要使用文本格式将发送的字符串转换为字节。一个好的文本格式是UTF-8。您可以像这样实现此转换:

bytes(string_to_convert, 'UTF-8')

或者,在代码的上下文中:

connectionSocket.send(bytes("HTTP/1.1 404 Not Found\r\n\r\n","UTF-8"))
connectionSocket.send(bytes("<html><head></head><body><h1>404 Not Found</h1></body></html>\r\n","UTF-8"))`
相关问题