当前位置: 首页 > 工具软件 > Netduino > 使用案例 >

来用C#在开源硬件Netduino上搞个httpserver吧

慕乐池
2023-12-01

来用C#在开源硬件Netduino上搞个httpserver吧       

        分类:            Netduino.Net MF 656人阅读 评论(4) 收藏 举报

     在Netduino上做一个httpserver并不是一件困难的事情,你只需要花点时间而已。

创建一个新的netduino plus的应用,不过你需要确定你选择的是netduino plus这个工程,那么很快你就可以做出一个web服务应用了。

在你的Main函数里,你可以先放下一下代码:

  1. OutputPort led = new OutputPort(Pins.ONBOARD_LED, false); 
OutputPort led = new OutputPort(Pins.ONBOARD_LED, false);

这段代码告诉我们,我们需要先声明一个输出端口,而且这个端口使用的是板子上的led灯。

下一步我们需要启动netduino的网络监听,端口80是一个默认的web服务端口,所以我们将使用80端口作为我们的http服务监听端口,当然了,你也可以使用别的端口作为你的httpserver的端口,比如说8080 那也行呀,不过这么做的话你的防火墙不放过你的80端口那你别怪到netduino上,要怪就怪你的网络和网管,听话点,用个80就行了,不必特立独行,如果你还不是很能够把握住的话,对么?

  1. // configure the port # (the standard web server port is 80) 
  2. int port = 80
// configure the port # (the standard web server port is 80)
int port = 80;


在这个例子里,插入5秒的等待延时,这是让netduino有足够的时间去获得动态分配的ip地址。

  1. Thread.Sleep(5000); 
Thread.Sleep(5000);

接着我们需要将所获得的ip地址通过debug的形式显示出来,当然,这需要运行在你的vs2010的debug模式下,查看你的调试窗口的内容,debug.print会让调试结果显示出来,

否则你没法去访问你的板子,因为你不知道netduino从你家的路由器里获得了什么地址。

  1. // display the IP address 
  2. Microsoft.SPOT.Net.NetworkInformation.NetworkInterface 
  3. networkInterface = 
  4. Microsoft.SPOT.Net.NetworkInformation.NetworkInterface. 
  5. GetAllNetworkInterfaces()[0]; 
  6. Debug.Print("my ip address: " + networkInterface.IPAddress.ToString()); 
// display the IP address
Microsoft.SPOT.Net.NetworkInformation.NetworkInterface
networkInterface =
Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.
GetAllNetworkInterfaces()[0];
Debug.Print("my ip address: " + networkInterface.IPAddress.ToString());

好了,你已经获得了ip地址了,你可以去启动一个socket去监听这个ip地址,并等待你的浏览器访问请求了

  1. // create a socket to listen for incoming connections 
  2. Socket listenerSocket = new Socket(AddressFamily.InterNetwork, 
  3. SocketType.Stream, 
  4. ProtocolType.Tcp); 
  5. IPEndPoint listenerEndPoint = new IPEndPoint(IPAddress.Any, port); 
  6. // bind to the listening socket 
  7. listenerSocket.Bind(listenerEndPoint); 
  8. // and start listening for incoming connections 
  9. listenerSocket.Listen(1); 
// create a socket to listen for incoming connections
Socket listenerSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
IPEndPoint listenerEndPoint = new IPEndPoint(IPAddress.Any, port);
// bind to the listening socket
listenerSocket.Bind(listenerEndPoint);
// and start listening for incoming connections
listenerSocket.Listen(1);

在代码里我们看到我们定义了一个listenerSocket的socket对象,然后根据listenerEndPoint的地址,listenerSocket绑定了netduino开发板上的listenerEndPoint地址,然后兵启动了它。现在netduino plus已经监听请求了,我们需要创建一个死循环,在那里你讲看到通过你的浏览器进入的请求。

  1. // listen for and process incoming requests 
  2. while (true
// listen for and process incoming requests
while (true)
{
}

在这个循环里,你将获得从客户端访问来的socket请求。

  1. // wait for a client to connect 
  2. Socket clientSocket = listenerSocket.Accept(); 
// wait for a client to connect
Socket clientSocket = listenerSocket.Accept();

然后,为了让所有的请求数据都顺利达到,你需要等待5秒的时间,

  1. // wait for data to arrive 
  2. bool dataReady = clientSocket.Poll(5000000, SelectMode.SelectRead); 
  3. // then you have a good connection. 
  4. if (dataReady && clientSocket.Available > 0) 
// wait for data to arrive
bool dataReady = clientSocket.Poll(5000000, SelectMode.SelectRead);
// then you have a good connection.
if (dataReady && clientSocket.Available > 0)
{
}

当你确定网络请求已经完成,你就可以开始去分析这些来的请求了,先把收到的请求放到一个buffer里吧

  1. byte[] buffer = new byte[clientSocket.Available]; 
  2. int bytesRead = clientSocket.Receive(buffer); 
byte[] buffer = new byte[clientSocket.Available];
int bytesRead = clientSocket.Receive(buffer);

就快完了,知道你们都看腻了,下一步我们要分析请求的参数,并将板子上的led灯的状态给修改过来。

  1. if (request.IndexOf("ON") >= 0) 
  2. led.Write(true); 
  3. else if (request.IndexOf("OFF") >= 0) 
  4. led.Write(false); 
if (request.IndexOf("ON") >= 0)
{
led.Write(true);
}
else if (request.IndexOf("OFF") >= 0)
{
led.Write(false);
}

现在你已经控制了板子上的led灯的开还是关,把led灯的开关状态给写入到字符串里,并通过http协议返回给请求的浏览器,让你及时知道板子是否关灯或者是开灯了
string statusText = "LED is " + (led.Read() ? "ON" : "OFF") + ".";

  1. string response = 
  2. "HTTP/1.1 200 OK\r\n"
  3. "Content-Type: text/html; charset=utf-8\r\n\r\n"
  4. "<html><head><title>Netduino Plus LED Sample</title></head>"
  5. "<body>" + statusText + "</body></html>"
string response =
"HTTP/1.1 200 OK\r\n" +
"Content-Type: text/html; charset=utf-8\r\n\r\n" +
"<html><head><title>Netduino Plus LED Sample</title></head>" +
"<body>" + statusText + "</body></html>";

当然了,你还需要通过刚才的客户端的socket将数据返回回去,
clientSocket.Send(System.Text.Encoding.UTF8.GetBytes(response));
}

当然了,做完了这些你得把你请求的socket关闭了吧。

  1. // important: close the client socket 
  2. clientSocket.Close(); 
// important: close the client socket
clientSocket.Close();

好了不来虚的,直接上代码吧

  1. using System; 
  2. using Microsoft.SPOT; 
  3. using Microsoft.SPOT.Hardware; 
  4. using SecretLabs.NETMF.Hardware.NetduinoPlus; 
  5. using System.Threading; 
  6. using System.Net.Sockets; 
  7. using System.Net; 
  8. namespace SocketServerSample 
  9.     public class program 
  10.     { 
  11.         public static void Main() 
  12.         { 
  13.             // write your code here 
  14.             // setup the LED and turn it off by default 
  15.             OutputPort led = new OutputPort(Pins.ONBOARD_LED, false); 
  16.             // configure the port # (the standard web server port is 80) 
  17.             int port = 80; 
  18.             // wait a few seconds for the Netduino Plus to get a network address. 
  19.             Thread.Sleep(5000); 
  20.             //Connecting to the Internet 69 
  21.             // display the IP address 
  22.             Microsoft.SPOT.Net.NetworkInformation.NetworkInterface networkInterface = Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0]; 
  23.             Debug.Print("my ip address: " + networkInterface.IPAddress.ToString()); 
  24.             // create a socket to listen for incoming connections 
  25.             Socket listenerSocket = new Socket(AddressFamily.InterNetwork, 
  26.             SocketType.Stream, ProtocolType.Tcp); 
  27.             IPEndPoint listenerEndPoint = new IPEndPoint(IPAddress.Any, port); 
  28.             // bind to the listening socket 
  29.             listenerSocket.Bind(listenerEndPoint); 
  30.             // and start listening for incoming connections 
  31.             listenerSocket.Listen(1); 
  32.             // listen for and process incoming requests 
  33.             while (true
  34.             { 
  35.                 // wait for a client to connect 
  36.                 Socket clientSocket = listenerSocket.Accept(); 
  37.                 // wait for data to arrive 
  38.                 bool dataReady = clientSocket.Poll(5000000, SelectMode.SelectRead); 
  39.                 // if dataReady is true and there are bytes available to read, 
  40.                 // then you have a good connection. 
  41.                 if (dataReady && clientSocket.Available > 0) 
  42.                 { 
  43.                     byte[] buffer = new byte[clientSocket.Available]; 
  44.                     int bytesRead = clientSocket.Receive(buffer); 
  45.                     string request = new string(System.Text.Encoding.UTF8.GetChars(buffer)); 
  46.                     if (request.IndexOf("ON") >= 0) 
  47.                     { 
  48.                         led.Write(true); 
  49.                     } 
  50.                     else if (request.IndexOf("OFF") >= 0) 
  51.                     { 
  52.                         led.Write(false); 
  53.                     } 
  54.                     string statusText = "LED is " + (led.Read() ? "ON" : "OFF") + "."
  55.                     //70 Getting Started with Netduino 
  56.                     // return a message to the client letting it 
  57.                     // know if the LED is now on or off. 
  58.                     string response = 
  59.                         "HTTP/1.1 200 OK\r\n"
  60.                         "Content-Type: text/html; charset=utf-8\r\n\r\n"
  61.                         "<html><head><title>Netduino Plus LED Sample</title></head>"
  62.                         "<body>" + statusText + "</body></html>"
  63.                     clientSocket.Send(System.Text.Encoding.UTF8.GetBytes(response)); 
  64.                 } 
  65.                 // important: close the client socket 
  66.                 clientSocket.Close(); 
  67.             } 
  68.         } 
  69.     } 
using System;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using SecretLabs.NETMF.Hardware.NetduinoPlus;
using System.Threading;
using System.Net.Sockets;
using System.Net;
namespace SocketServerSample
{
    public class program
    {
        public static void Main()
        {
            // write your code here
            // setup the LED and turn it off by default
            OutputPort led = new OutputPort(Pins.ONBOARD_LED, false);
            // configure the port # (the standard web server port is 80)
            int port = 80;
            // wait a few seconds for the Netduino Plus to get a network address.
            Thread.Sleep(5000);
            //Connecting to the Internet 69
            // display the IP address
            Microsoft.SPOT.Net.NetworkInformation.NetworkInterface networkInterface = Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0];
            Debug.Print("my ip address: " + networkInterface.IPAddress.ToString());
            // create a socket to listen for incoming connections
            Socket listenerSocket = new Socket(AddressFamily.InterNetwork,
            SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint listenerEndPoint = new IPEndPoint(IPAddress.Any, port);
            // bind to the listening socket
            listenerSocket.Bind(listenerEndPoint);
            // and start listening for incoming connections
            listenerSocket.Listen(1);
            // listen for and process incoming requests
            while (true)
            {
                // wait for a client to connect
                Socket clientSocket = listenerSocket.Accept();
                // wait for data to arrive
                bool dataReady = clientSocket.Poll(5000000, SelectMode.SelectRead);
                // if dataReady is true and there are bytes available to read,
                // then you have a good connection.
                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)
                    {
                        led.Write(true);
                    }
                    else if (request.IndexOf("OFF") >= 0)
                    {
                        led.Write(false);
                    }
                    string statusText = "LED is " + (led.Read() ? "ON" : "OFF") + ".";
                    //70 Getting Started with Netduino
                    // return a message to the client letting it
                    // know if the LED is now on or off.
                    string response =
                        "HTTP/1.1 200 OK\r\n" +
                        "Content-Type: text/html; charset=utf-8\r\n\r\n" +
                        "<html><head><title>Netduino Plus LED Sample</title></head>" +
                        "<body>" + statusText + "</body></html>";
                    clientSocket.Send(System.Text.Encoding.UTF8.GetBytes(response));
                }
                // important: close the client socket
                clientSocket.Close();
            }
        }
    }
}


怎么样,你成功了吗??如果没有开发板你可以在我那买一个,当然,没有开发板在vs2010的模拟器上也是可以跑的,去尝试一下吧

你会感觉好像开发硬件和跟你平时写一个普通的c#代码没啥区别,所以用netduino板子开发硬件可以抹平你和硬件之间的距离。netduino的世界很精彩,期待您的参与。

忘记了,做个广告吧,为我的烂淘宝店,这是我开始尝试电商的一个通道,也希望能找到合适你用的东西。

 类似资料: