我正在处理我的第一个 Pytn 套接字编程代码,我无法弄清楚什么是错的。我输入这个程序正在运行的服务器的 IP地址以及端口号和我试图接收的文件。我应该在浏览器中接收文件,套接字应该关闭。相反,服务器打印出打印行 'Ready to serve...' 三次,在浏览器上显示 '404 Not Found',并且从不关闭套接字。有人有想法吗?
#import socket module
from socket import *
serverSocket = socket(AF_INET, SOCK_STREAM)
#Prepare a sever socket
serverSocket.bind(('', 12006))
serverSocket.listen(1)
while True:
print 'Ready to serve...'
#Establish the connection
connectionSocket, addr = serverSocket.accept()
try:
message = connectionSocket.recv(1024)
filename = message.split()[1]
f = open(filename[1:])
outputdata = f.read()
f.close()
#Send one HTTP header line into socket
connectionSocket.send('HTTP/1.0 200 OK\r\n\r\n')
#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:
#Send response message for file not found
connectionSocket.send('404 Not Found')
#Close client socket
connectionSocket.close()
serverSocket.close()
谢谢大家的帮助。我想出了什么问题。我已经将我的 HTML 重命名为“HelloWorld.html”,然后 Windows 自动将.html 添加到文件的末尾。因此,为了访问我需要在 HelloWorld.html.html 中键入的文件。我更改了文件名,然后此代码工作完美。
此代码应该工作:
# pytn 3
from socket import *
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind(('127.0.0.1', 5500))
serverSocket.listen(1)
while True:
print("Server is running")
connectionSocket, addr = serverSocket.accept()
try:
message = connectionSocket.recv(1024)
filename = message.split()[1].decode('utf-8').strip("/")
print(filename)
f = open(filename)
outputdata = f.read()
f.close()
connectionSocket.send('HTTP/1.0 200 OK\r\n\r\n'.encode())
for i in range(0, len(outputdata)):
connectionSocket.send(outputdata[i].encode())
connectionSocket.close()
except IOError:
connectionSocket.send('404 Not Found'.encode())
connectionSocket.close()
serverSocket.close()
在此行之前filename = message.split()[1]
print(message)
在这一行之后filename = message.split()[1]
print(filename)
我认为错误是在这一行。
本站系公益性非盈利分享网址,本文来自用户投稿,不代表边看边学立场,如若转载,请注明出处
评论列表(26条)