关于用Python编写的简单服务器的问题

4 投票
2 回答
18094 浏览
提问于 2025-04-16 04:51

这是一个简单的服务器。当你在浏览器里输入服务器的地址时,它会返回一个状态码和请求的HTML内容。但是,当我加上这句“connectionSocket.send('HTTP/1.1 200 OK')”后,就什么都没返回。把它去掉后,HTML内容就能返回了。还有一个问题是,当我通过浏览器发送请求时,会有两个连接发送到服务器,其中一个显示它想找一个叫favicon.ico的文件,但当然会出现IOError,因为我的服务器根目录下没有这个文件。代码附在下面,谢谢大家的帮助。


#import socket module

from socket import *
serverSocket = socket(AF_INET,SOCK_STREAM)
#prepare a server socket

serverSocket.bind(('192.168.0.101', 8765))
serverSocket.listen(1)

while True:

    #Establish the connection

    print 'Ready to serve...'
    connectionSocket,addr =  serverSocket.accept()
    print 'connected from',addr
    try:
        message = connectionSocket.recv(1024)
        filename = message.split()[1]
        print filename
        f = open(filename[1:])
        outputdata = f.read()

        #Send one HTTP header line into socket

        #connectionSocket.send('HTTP/1.1 200 OK')

        #Send the content of the requested file to the client

        for i in range(0,len(outputdata)):
            connectionSocket.send(outputdata[i])
        connectionSocket.close()
    except IOError:
        print 'IOError'

        #Send response message for file not found

        connectionSocket.send('file not found')

        #Close Client socket

        connectionSocket.close()
serverSocket.close()

2 个回答

0

你有没有试过把返回的结果从 string 转换成 bytes 呢?

把这个:

connectionSocket.send('HTTP/1.1 200 OK\r\n\r\n')

换成这个:

connectionSocket.send(bytes('HTTP/1.1 200 OK\r\n\r\n','UTF-8'))
6

你需要在HTTP头的末尾添加两个换行符(\r\n\r\n):

connectionSocket.send('HTTP/1.1 200 OK\r\n\r\n')

另外,你可能应该使用一个更高级的库来编写你的HTTP服务器...

撰写回答