2015-10-01 141 views
0

我正在寫一個簡單的網絡服務器。這是Python代碼,我有:網絡服務器 - 如何指定服務器使用

import http.server 

from os import curdir, sep 

class RequestHandler(http.server.BaseHTTPRequestHandler): 
    def do_GET(self): 
     if self.path.endswith(".php"): 
      f = open(curdir + sep + self.path) 

      self.send_response(200); 
      self.send_header("Content-type", "text/php") 
      self.end_headers() 

      self.wfile.write(f.read()) 
      f.close() 

     else: 
      self.send_error(404, "Cannot open non-html file") 

httpd = http.server.HTTPServer(("", 8000), RequestHandler) 
httpd.serve_forever() 

這是HTML代碼:

<!doctype html> 
<html lang="en"> 
    <head> 
     <meta charset="UTF-8"> 
     <title>Hello</title>  

     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> 
    </head> 

    <body> 
     <input type="button" value="Click me" id="button"> 

     <script> 

      var buttonOnClick = 
       function() { 

        var updateButton = 
         function(result) { 
          $("#button").replaceWith("<p>" + result + "<p>"); 
          }; 


        $.get("text.php", updateButton); 
       }; 

      $("#button").click(buttonOnClick); 

     </script> 
    </body> 
</html> 

text.php

<?php 
     echo "Hello!"; 
?> 

當我與Apache上運行此,我得到的預期成績。該按鈕變成「你好!」當你點擊它。但是,當我使用Apache運行它時,頁面顯示ERR_CONNECTION_REFUSED錯誤。這告訴我,我的網頁使用Apache作爲服務器,而不是我的Python代碼。我無法弄清楚如何讓我的HTML和jQuery代碼使用我的自定義web服務器而不是Apache。這可能是一個非常簡單的問題,但我很難過。

如果我的代碼中有任何可以改進的地方,請告訴我。

+0

定製服務器在端口8000。你把'運行:8000'在URL中的服務器名稱後? – Barmar

+0

我嘗試使用'https:// localhost:8000/webprograms/testwebserver/index.html'。它給了我一個SSL連接錯誤。 – M3579

回答

1

端口號在URL中的主機名後面,而不是在末尾。

而且由於您的HTTP服務器沒有啓用SSL,您必須使用http:作爲協議,而不是https:

所以URL應該是http://localhost:8000/webprograms/testwebserver/index.html

+0

它表示「沒有收到數據」,我認爲這是程序員錯誤。我如何在Python代碼中解決這個問題? – M3579

+0

當您運行網絡服務器時,「webprograms」是您當前目錄的子目錄嗎? – Barmar

+0

所有這些文件所在的目錄是'C:\ xampp \ htdocs \ WebPrograms \ TestWebServer'。 – M3579