我已经成功地从浏览器访问我的网络服务器,在服务器上下载了一个文件,并使用chrome正确查看了该文件。但是,当服务器停留约。 20秒,它会因IndexError而崩溃。
from socket import *
serverport = 972
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind(('', serverport))
serverSocket.listen(1)
print 'Standing by...'
while True:
#Establish the connection
connectionSocket, addr = serverSocket.accept()
try:
message = connectionSocket.recv(1024)
filename = message.split()[1]
f = open(filename[1:])
outputdata = f.read()
for i in range(0, len(outputdata)):
connectionSocket.send(outputdata[i])
print 'Success! File sent!'
connectionSocket.close()
except IOError:
errormessage = 'Error 404 - File not found'
connectionSocket.send(errormessage)
我得到的输出如下:
Standing by..
Success! File sent! #sent everytime i request the webpage on the client localhost:80/helloworld.html
Traceback (most recent call last):
File "C:/Users/Nikolai/Dropbox/NTNU/KTN/WebServer/TCPServer.py", line 14, in <module>
filename = message.split()[1]
IndexError: list index out of range
答案 0 :(得分:1)
这可能是关闭连接的客户端。连接完成后,会收到一个空字符串''
。
''.split()[1]
将失败并显示index out of range
。我的建议是试试这个补丁:
message = connectionSocket.recv(1024)
if not message:
# do something like return o continue
顺便说一句,你应该从你的套接字recv
,直到得到空字符串。在您的代码中,如果请求大于1024
会发生什么?这样的事情可以做到:
try:
message = ''
rec = connectionSocket.recv(1024)
while rec:
rec = connectionSocket.recv(1024)
message += rec
if not message:
connectionSocket.close()
continue
filename = message.split()[1]
f = open(filename[1:])
outputdata = f.read()
for i in range(0, len(outputdata)):
connectionSocket.send(outputdata[i])
print 'Success! File sent!'
connectionSocket.close()
您应该阅读Socket Programming HOWTO,特别是创建多线程服务器的部分,这可能就是您想要的那样:)
希望这有帮助!