2014-11-03 39 views
0

我正在構建一個Python Web服務器,並需要它來呈現HTML元素。截至目前,該程序通過[email protected]: ./server.py --base=home/website/html/ --port=8080,然後在網絡瀏覽器中實現,連接到URL http://localhost:8080/index.html。然而,該網頁上顯示的唯一東西是HTTP/1.1 200 OK,這很好,因爲這意味着我可以連接到服務器。我現在需要的是瀏覽器能夠呈現HTML,CSS和相應的Javascript組件的內容。有什麼建議麼?我一直在撓撓我的大腦,試圖找出如何做到這一點。Python Web服務器HTML呈現

我已包括下面我的代碼:

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()) 

回答

0

是否 「回家/網站/ HTML/index.html的」 在你的服務器是否存在?我試過你的代碼。在訪問現有文件時,它工作正常。但是對於提供不存在的文件,代碼中存在一個錯誤。發送文件內容的代碼應該是最內層的「嘗試」塊內:

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建立一個Web服務器實在是太低級。你有很多額外的工作要做,例如手動編寫通用的http頭文件。嘗試一些更高級別的庫/框架,例如

+0

的位置和文件確實存在,我試着與一對夫婦亂搞在我的電腦上的其他位置,但仍然是相同的結果。這是一個類的項目,這就是爲什麼我使用套接字模塊。我們被明確告知不要在這個項目中使用http.client,http.server,socketserver或urllib模塊。 – superfluousAM 2014-11-03 22:00:33

+0

'print(dest_file)'的輸出是什麼' – ZZY 2014-11-03 23:54:17

+0

它打印出「/index.html」或我指定的任何文件 – superfluousAM 2014-11-14 01:49:38