有关于python编写的简单服务器的问题

2024-04-19 06:46:47 发布

您现在位置:Python中文网/ 问答频道 /正文

这是一个简单的服务器。当您打开浏览器时,输入服务器的地址,它将响应一个状态码和所请求的html的内容。但是当我添加这个句子“connectionSocket.send('HTTP/1.1200 OK')”时,没有返回任何内容。当我删除它时,html返回。另一个问题是当我通过web浏览器发送请求时,有两个连接被发送到服务器,其中一个显示它想要找到一个名为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()


Tags: the服务器sendhttpmessageclosesocketfilename
2条回答

您需要将新行(\r\n\r\n)添加到HTTP头的末尾:

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

另外,您可能应该使用更高级别的库来编写HTTP服务器。。。

是否尝试将返回值从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'))

相关问题 更多 >