Chrome版本70.0.3538.102
以下是我的简单http服务器(在python中(的代码
from socket import *
import sys
server_socket = socket(AF_INET, SOCK_STREAM)
server_socket.bind(('localhost', 8080))
server_socket.listen(5)
print('Starting up http-server, serving ./')
print('Available on:')
print(' http://localhost:8080')
print('Hit CTRL-BREAK to stop the server')
while True:
connection_socket, address = server_socket.accept()
print()
print('Connected by: ', address[0] + ':' + str(address[1]))
try:
message = connection_socket.recv(1024)
filename = message.split()[1]
print('Filename to get: ', filename[1:].decode())
f = open(filename[1:], 'rb')
output_data = f.read()
connection_socket.send('HTTP/1.1 200 OKrnrn'.encode())
connection_socket.send(output_data)
connection_socket.send('rn'.encode())
connection_socket.close()
except IOError:
connection_socket.send('HTTP/1.1 404 Not Foundrnrn'.encode())
connection_socket.send('404 Not Found'.encode())
connection_socket.send('rn'.encode())
connection_socket.close()
server_socket.close()
sys.exit()
我用Microsoft Edge测试了它,它的输出如下:
Starting up http-server, serving ./
Available on:
http://localhost:8080
Hit CTRL-BREAK to stop the server
Connected by: 127.0.0.1:60998
Filename to get: test.html
但当我把浏览器切换到Chrome浏览器后,发生了一件非常奇怪的事情。
Starting up http-server, serving ./
Available on:
http://localhost:8080
Hit CTRL-BREAK to stop the server
Connected by: 127.0.0.1:61332
Filename to get: test.html
Connected by: 127.0.0.1:61333
Filename to get: favicon.ico
Connected by: 127.0.0.1:61335
Traceback (most recent call last):
File "http-server.py", line 20, in <module>
filename = message.split()[1]
IndexError: list index out of range
Chrome似乎打开了三个连接,但只使用了其中的两个。上次连接没有向服务器发送任何消息。
您可以使用except IndexError:
修复此错误
修复代码如下:
from socket import *
import sys
server_socket = socket(AF_INET, SOCK_STREAM)
server_socket.bind(('localhost', 8080))
server_socket.listen(5)
print('Starting up http-server, serving ./')
print('Available on:')
print(' http://localhost:8080')
print('Hit CTRL-BREAK to stop the server')
while True:
connection_socket, address = server_socket.accept()
print()
print('Connected by: ', address[0] + ':' + str(address[1]))
try:
message = connection_socket.recv(1024)
filename = message.split()[1]
print('Filename to get: ', filename[1:].decode())
f = open(filename[1:], 'rb')
output_data = f.read()
connection_socket.send('HTTP/1.1 200 OKrnrn'.encode())
connection_socket.send(output_data)
connection_socket.send('rn'.encode())
connection_socket.close()
except IOError:
connection_socket.send('HTTP/1.1 404 Not Foundrnrn'.encode())
connection_socket.send('404 Not Found'.encode())
connection_socket.send('rn'.encode())
connection_socket.close()
except IndexError:
# what you want to do when request is invalid
server_socket.close()
sys.exit()