简单 Python TCP 服务器未发送整个网页

Simple Python TCP Server Not Sending the Entire Web Page

我是一名初学者 compsci 学生,我正在尝试在 python 中编写一个简单的服务器代码,该服务器采用存储在同一目录中的 .HTML 页面并将其发送到客户端使用 TCP 连接的同一网络。

这是我的代码:

from socket import *

serverPort = 8000
serverSocket = socket(AF_INET, SOCK_STREAM)
# Prepare a sever socket
serverSocket.bind(('', serverPort))  # binds socket to port 8000
serverSocket.listen(1)  # waiting for client to initiate connection

while True:
    # Establish the connection
    print('Ready to serve...')
    connectionSocket, addr = serverSocket.accept()
    try:

        message = connectionSocket.recv(1024)
        filename = message.split()[1]

        f = open(filename[1:].decode())
        outputdata = f.read()

        # Send one HTTP header line into socket
        http_response = 'HTTP/1.1 200 OK\n'

        connectionSocket.send(http_response.encode())

        # 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:
        connectionSocket.send("\r\n".encode())
        # DO LATER
serverSocket.close()
sys.exit()

这是我的简单 html 页面:

<!DOCTYPE html>
<html>
  <body>
    <h1>My First Web Page</h1>

    <p>You have successfully accessed the Web Server</p>
  </body>
</html>

到目前为止,每当我 运行 我的服务器并将我的浏览器指向它时,我只会得到以下服务:

<p>You have successfully accessed the Web Server</p>

以及此后的 body 和 html 标签。检查页面源没有 header.

我 运行 Wireshark 在尝试访问我的服务器时确实看起来我只是通过“您已成功访问 Web 服务器”及以后发送。尽管打印功能显示我确实通过 TCP 连接发送文件中的所有数据,但这是事实。

有人知道问题出在哪里吗?

我会使用 http.server

import http.server
import socketserver

PORT = 8080
Handler = http.server.SimpleHTTPRequestHandler

with socketserver.TCPServer(("", PORT), Handler) as httpd:
    httpd.serve_forever()

来源:https://www.afternerd.com/blog/python-http-server/

发送协议应答和 headers 后,实际响应在两个 \r\n 序列后出现。

使用这个固定代码:

from socket import *

serverPort = 8000
serverSocket = socket(AF_INET, SOCK_STREAM)
# Prepare a sever socket
serverSocket.bind(('', serverPort))  # binds socket to port 8000
serverSocket.listen(1)  # waiting for client to initiate connection

while True:
    # Establish the connection
    print('Ready to serve...')
    connectionSocket, addr = serverSocket.accept()
    try:

        message = connectionSocket.recv(1024)
        filename = message.split()[1]

        f = open(filename[1:].decode())
        outputdata = f.read()

        # Send one HTTP header line into socket
        http_response = 'HTTP/1.1 200 OK\n'

        connectionSocket.send(http_response.encode())
        connectionSocket.send("\r\n".encode())
        connectionSocket.send("\r\n".encode())

        # Send the content of the requested file to the client
        for i in range(0, len(outputdata)):
            connectionSocket.send(outputdata[i].encode())

        connectionSocket.close()
    except IOError:
        # DO LATER
serverSocket.close()
sys.exit()