由于我是编程新手,我可能还没有检测到其他错误,所以如果你发现任何菜鸟错误或不好的风格请指出。我正在尝试实现一个简单的Web服务器,但在服务器创建HTTP响应消息的部分继续收到缩进错误,该消息包含前面标题行的请求文件。
from socket import *
import sys
host = 'localhost'
serverPort = int(sys.argv[1])
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind((host,serverPort))
serverSocket.listen(1)
while True:
connectionSocket, addr = serverSocket.accept()
try:
#if received correct stuff
File_Wanted = connectionSocket.recv(1024)
File_Name = File_Wanted.split()[1]
#open and read line in index.htm
File = open('index.htm','r')
output = File.read()
#should I close it here or somewhere else?
File.close()
#take care of header first
connectionSocket.send('HTTP/1.0 200 OK\r\n')
#looks good, then send to client(browser)
for i in range(0, len(output)):
connectionSocket.send(output[i])
connectionSocket.close()
IOError:
#Send response message for file not found
connectionSocket.send('404 Not Found')
#Close client socket
connectionSocket.close()
serverSocket.close()
当我建立崇高时,我得到了。
connectionSocket.send(output[i])
^
IndentationError:期待一个带有标号的块
答案 0 :(得分:0)
Python使用空格来定义块,你需要在for
语句之后缩进行:
for i in range(0, len(output)):
connectionSocket.send(output[i])
connectionSocket.close()
并且在检查错误之前需要except
语句:
except IOError: