2013-08-05 41 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