2013-08-05 29 views
1

我正在使用網絡服務器來控制房屋內的設備,運行.netMF(netduino plus 2)的微控制器。下面的代碼將一個簡單的html頁面寫入到通過互聯網連接到微控制器的設備。用微控制器寫一個完整的網站插座

 while (true) 
      { 
       Socket clientSocket = listenerSocket.Accept(); 
       bool dataReady = clientSocket.Poll(5000000, SelectMode.SelectRead); 
       if (dataReady && clientSocket.Available > 0) 
       { 
        byte[] buffer = new byte[clientSocket.Available]; 
        int bytesRead = clientSocket.Receive(buffer); 
        string request = 
        new string(System.Text.Encoding.UTF8.GetChars(buffer)); 
        if (request.IndexOf("ON") >= 0) 
        { 
         outD7.Write(true); 
        } 
        else if (request.IndexOf("OFF") >= 0) 
        { 
         outD7.Write(false); 
        } 
        string statusText = "Light is " + (outD7.Read() ? "ON" : "OFF") + "."; 

        string response = WebPage.startHTML(statusText, ip); 
        clientSocket.Send(System.Text.Encoding.UTF8.GetBytes(response)); 
       } 
       clientSocket.Close(); 
      } 

public static string startHTML(string ledStatus, string ip) 
     { 
      string code = "<html><head><title>Netduino Home Automation</title></head><body> <div class=\"status\"><p>" + ledStatus + " </p></div>  <div class=\"switch\"><p><a href=\"http://" + ip + "/ON\">On</a></p><p><a href=\"http://" + ip + "/OFF\">Off</a></p></div></body></html>"; 
      return code; 
     } 

這很好用,所以我寫了一個完整的jQuery手機網站來代替簡單的html。這個網站存儲在設備的SD卡上,並使用下面的代碼,應該寫完整的網站,而不是上面的簡單html。

但是,我的問題是netduino只將單個HTML頁面寫入瀏覽器,並沒有HTML中引用的任何JS/CSS樣式文件。我怎樣才能確保瀏覽器讀取所有這些文件,作爲一個完整的網站?

我寫來讀取SD網站的代碼是:

private static string getWebsite() 
     { 
      try 
      { 
       using (StreamReader reader = new StreamReader(@"\SD\index.html")) 
       { 
        text = reader.ReadToEnd(); 
       } 
      } 
      catch (Exception e) 
      { 
       throw new Exception("Failed to read " + e.Message); 
      } 

      return text; 
     } 

我更換串碼=「等位與

string code = getWebsite(); 

回答

0

我怎樣才能確保瀏覽器讀取所有這些文件,作爲完整的網站?

不是已經?使用一個HTTP調試工具,如Fiddler。從我的代碼中讀取時,您的listenerSocket應該在端口80上偵聽。您的瀏覽器將首先檢索getWebsite調用的結果並解析HTML。

然後,它會觸發更多請求,因爲它會在HTML中找到CSS和JS引用(未顯示)。就我們從您的代碼中看到的情況而言,這些請求將再次收到getWebsite調用的結果。

您需要解析傳入的HTTP請求以查看正在請求的資源。如果您運行的.NET實現支持HttpListener類(和它seems to),它會變得更容易。

+0

謝謝,我今晚會測試一下。我認爲這個問題很可能在getWebsite調用中,因爲streamreader可能只是將html頁面讀爲一串文本 – Wayneio