Python网页服务器HTML渲染

0 投票
1 回答
2222 浏览
提问于 2025-05-01 05:34

我正在搭建一个Python的网页服务器,需要它能够显示HTML元素。目前我的程序是通过命令 aj@ubuntu: ./server.py --base=home/website/html/ --port=8080 来运行的,然后在网页浏览器中访问 http://localhost:8080/index.html。不过,现在在网页上显示的内容只有 HTTP/1.1 200 OK,这说明我成功连接到了服务器,这很好。但我现在需要的是让浏览器能够显示HTML、CSS和相关的JavaScript内容。有没有什么建议?我一直在思考该怎么做。

我把我的代码放在下面:

import socket
import sys
if not sys.version_info[:2] == (3,4):
 print("Error: need Python 3.4 to run program")
 sys.exit(1)
else:
 print("Using Python 3.4 to run program")
import argparse

def main():

parser = argparse.ArgumentParser(description='Project 1 Web Server for COMP/ECPE 177')
parser.add_argument('--version', help='Show program\'s version number and exit')
parser.add_argument('--base', action='store', help='Base directory containing website', metavar='/path/to/directory')
parser.add_argument('--port', action='store', type=int, help='Port number to listen on', metavar='####')
args = parser.parse_args()
#parser.print_help()
#print(args.port, args.base)


# Create TCP socket
try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
except socket.error as msg:
    print("Error: could not create socket")
    print("Description: " + str(msg))
    sys.exit()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

# Bind to listening port
try:
    host=''  # Bind to all interfaces
    s.bind((host,args.port))
except socket.error as msg:
    print("Error: unable to bind on port %d" % args.port)
    print("Description: " + str(msg))
    sys.exit()

# Listen
try:
    backlog=10  # Number of incoming connections that can wait
                # to be accept()'ed before being turned away
    s.listen(backlog)
except socket.error as msg:
    print("Error: unable to listen()")
    print("Description: " + str(msg))
    sys.exit()    

print("Listening socket bound to port %d" % args.port)

while 1:
# Accept an incoming request
    try:
        (client_s, client_addr) = s.accept()
        # If successful, we now have TWO sockets
        #  (1) The original listening socket, still active
        #  (2) The new socket connected to the client
    except socket.error as msg:
        print("Error: unable to accept()")
        print("Description: " + str(msg))
        sys.exit()

    print("Accepted incoming connection from client")
    print("Client IP, Port = %s" % str(client_addr))

    # Receive data
    try:
        buffer_size=4096
        raw_bytes = client_s.recv(buffer_size)
    except socket.error as msg:
        print("Error: unable to recv()")
        print("Description: " + str(msg))
        sys.exit()

    string_unicode = raw_bytes.decode('ascii')
    print("Received %d bytes from client" % len(raw_bytes))
    print("Message contents: %s" % string_unicode)

    request = str.split(string_unicode)
    #print(request)
    hcmd = request[0]
    filep = request[1]
    protocol = request[2]
    print(filep)

    if filep == '/':
        filep = '/index.html'

    if hcmd == 'GET':
        dest_file = None
        try:
            try:
                dest_file = open(args.base + filep, 'rb')
            except (OSError, IOError) as msg:
                msg = 'HTTP/1.1 404 Request Not Found\r\n\r\n'
                statcode = 1 #404 request not found
                rb1 = bytes(msg, 'ascii')
                client_s.sendall(rb1)

            message_send = 'HTTP/1.1 200 OK\r\n\r\n'
            statcode = 0 #200 OK
            rb2 = bytes(message_send, 'ascii')
            client_s.sendall(rb2)

            if dest_file is not None:
                datasend = dest_file.read()
                client_s.sendall(datasend)
                dest_file.close()
            print(dest_file)
            print(statcode)

        except socket.error as msg:
            msg2 = "Error: "
            sys.exit()

    else:
        message_send = 'HTTP/1.1 501 Not Implemented\r\n\r\n'
        statuscode = 2 #501 not implemented
        rb3 = bytes(message_send, 'ascii')
        client_s.sendall(rb3)
    client_s.close()

#Close both sockets
try:
   s.close()
except socket.error as msg:
   print("Error: unable to close() socket")
   print("Description: " + str(msg))
   sys.exit()

print("Sockets closed, now exiting")

if __name__ == "__main__":
 sys.exit(main())
暂无标签

1 个回答

0

你的服务器上有“home/website/html/index.html”这个文件吗?我试过你的代码。当我访问一个存在的文件时,一切正常。但是当要处理不存在的文件时,你的代码就有问题了。发送文件内容的代码应该放在最里面的那个'try'块里:

try:
    dest_file = open(args.base + filep, 'rb')

    #---------Should be put here-----------
    message_send = 'HTTP/1.1 200 OK\r\n\r\n'
    statcode = 0 #200 OK
    rb2 = bytes(message_send, 'ascii')
    client_s.sendall(rb2)

    if dest_file is not None:
        datasend = dest_file.read()
        client_s.sendall(datasend)
        dest_file.close()
    print(dest_file)
    print(statcode)
    #--------------------------------------

except (OSError, IOError) as msg:
    msg = 'HTTP/1.1 404 Request Not Found\r\n\r\n'
    statcode = 1 #404 request not found
    rb1 = bytes(msg, 'ascii')
    client_s.sendall(rb1)

另外,如果不是为了学习,使用socket来搭建一个网页服务器其实太基础了。你需要做很多额外的工作,比如手动编写常见的http头信息。可以试试一些更高级的库或框架,比如:

撰写回答