【发布时间】:2020-06-03 04:22:01
【问题描述】:
我正在学习网络入门课程,我们正在学习如何编写基本的 TCP 服务器。
我的设置: 该分配要求一个服务器,即一次处理一个 HTTP 请求的 Web 服务器。我的 Web 服务器应该“接受并解析 HTTP 请求,从服务器的文件系统中获取请求的文件,创建一个 HTTP 响应消息,该消息由请求的文件和标题行组成,然后将响应直接发送给客户端。如果请求文件不存在于服务器中,服务器应将 HTTP “404 Not Found”消息发送回客户端。”我用 Python 编写了服务器(见下文),据我所知,代码是准确的。在同一个目录中,我还创建了一个简单的 hello world html 文件,所以我有一些要求。
运行我的服务器: 当我运行代码时,终端期望“准备好服务...”消息并监听连接。这是正确的。
然后,当我在浏览器中输入 URL 时(我尝试了 http://localhost:1001 和 http://localhost:1001/HelloWorld.html),浏览器说它无法连接。
Unable to connect screen from browser
我很确定我要么没有作为客户端正确连接到服务器,要么我的 Windows 机器没有正确设置,但是任何关于如何连接并将我的请求通过服务器的建议都会非常有用赞赏。
#import socket module
from socket import *
import sys # In order to terminate the program
serverSocket = socket(AF_INET, SOCK_STREAM)
#Prepare a sever socket
serverPort = 1001
serverSocket.bind(('',serverPort))
serverSocket.listen(1)
while True:
#Establish the connection
print('Ready to serve...')
connectionSocket, addr = serverSocket.accept()
try:
message = connectionSocket.recv(1024).decode()
filename = message.split()[1]
f = open(filename[1:])
outputdata = f.read()
#Send one HTTP header line into socket
#Fill in start
header = 'HTTP/1.1 200 OK\n'
connectionSocket.send(header.encode())
#Fill in end
#Send the content of the requested file to the client
for i in range(0, len(outputdata)):
connectionSocket.send(outputdata[i].encode())
connectionSocket.send("\r\n".encode())
connectionSocket.close()
except IOError:
#Send response message for file not found (404)
#Fill in start
error = 'HTTP/1.1 404 Not Found'
connectionSocket.send(error.encode())
#Fill in end
#Close client socket
#Fill in start
connectionSocket.close()
#Fill in end
serverSocket.close()
sys.exit() #Terminate the program after sending the corresponding data
【问题讨论】:
-
您在运行服务器时是否遇到绑定错误?你应该有。 1001是保留端口,和1024以下的所有端口一样。
-
取决于他的环境,在 Windows 上,我在非管理员命令行上运行他的脚本没有问题。
标签: python networking server