Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Python Web服务器HTML呈现_Javascript_Python_Html_Css_Sockets - Fatal编程技术网

Javascript Python Web服务器HTML呈现

Javascript Python Web服务器HTML呈现,javascript,python,html,css,sockets,Javascript,Python,Html,Css,Sockets,我正在构建一个Python web服务器,需要它来呈现HTML元素。目前,该程序通过aj@ubuntu:./server.py--base=home/website/html/--port=8080然后在web浏览器中连接到URLhttp://localhost:8080/index.html。但是,该网页上显示的唯一内容是HTTP/1.1200 OK,这很好,因为这意味着我能够连接到服务器。我现在所需要的只是浏览器,以便能够呈现HTML、CSS和相应Javascript组件的内容。有什么建议吗

我正在构建一个Python web服务器,需要它来呈现HTML元素。目前,该程序通过
aj@ubuntu:./server.py--base=home/website/html/--port=8080
然后在web浏览器中连接到URL
http://localhost:8080/index.html
。但是,该网页上显示的唯一内容是
HTTP/1.1200 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())
您的服务器中是否存在“home/website/html/index.html”?我试过你的密码。访问现有文件时,它工作正常。但是对于服务不存在的文件,代码中有一个bug。用于发送文件内容的代码应位于最内部的“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)
此外,如果不是为了学习,那么使用套接字构建web服务器的级别实在太低了。您有很多额外的工作要做,例如手动编写公共http头。尝试一些更高级的库/框架,例如

  • 内置http服务器:
  • 流行的web框架Django:

位置和文件确实存在,我曾尝试在我的计算机上与其他几个位置混在一起,但结果仍然相同。这是一个类的项目,所以这就是我使用sockets模块的原因。我们被明确告知不要在这个项目中使用http.client、http.server、socketserver或urllib模块。打印(dest_文件)It打印出“/index.html”或我指定的任何文件的输出是什么