来用C#在开源硬件Netduino上搞个httpserver吧
在Netduino上做一个httpserver并不是一件困难的事情,你只需要花点时间而已。
创建一个新的netduino plus的应用,不过你需要确定你选择的是netduino plus这个工程,那么很快你就可以做出一个web服务应用了。
在你的Main函数里,你可以先放下一下代码:
- 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就行了,不必特立独行,如果你还不是很能够把握住的话,对么?
- // configure the port # (the standard web server port is 80)
- int port = 80;
// configure the port # (the standard web server port is 80)
int port = 80;
在这个例子里,插入5秒的等待延时,这是让netduino有足够的时间去获得动态分配的ip地址。
- Thread.Sleep(5000);
Thread.Sleep(5000);
接着我们需要将所获得的ip地址通过debug的形式显示出来,当然,这需要运行在你的vs2010的debug模式下,查看你的调试窗口的内容,debug.print会让调试结果显示出来,
否则你没法去访问你的板子,因为你不知道netduino从你家的路由器里获得了什么地址。
- // 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());
// 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地址,并等待你的浏览器访问请求了
- // 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);
// 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已经监听请求了,我们需要创建一个死循环,在那里你讲看到通过你的浏览器进入的请求。
- // listen for and process incoming requests
- while (true)
- {
- }
// listen for and process incoming requests
while (true)
{
}
在这个循环里,你将获得从客户端访问来的socket请求。
- // wait for a client to connect
- Socket clientSocket = listenerSocket.Accept();
// wait for a client to connect
Socket clientSocket = listenerSocket.Accept();
然后,为了让所有的请求数据都顺利达到,你需要等待5秒的时间,
- // wait for data to arrive
- bool dataReady = clientSocket.Poll(5000000, SelectMode.SelectRead);
- // then you have a good connection.
- 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里吧
- byte[] buffer = new byte[clientSocket.Available];
- int bytesRead = clientSocket.Receive(buffer);
byte[] buffer = new byte[clientSocket.Available];
int bytesRead = clientSocket.Receive(buffer);
就快完了,知道你们都看腻了,下一步我们要分析请求的参数,并将板子上的led灯的状态给修改过来。
- if (request.IndexOf("ON") >= 0)
- {
- led.Write(true);
- }
- else if (request.IndexOf("OFF") >= 0)
- {
- 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") + ".";
- 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>";
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关闭了吧。
- // important: close the client socket
- clientSocket.Close();
// important: close the client socket
clientSocket.Close();
好了不来虚的,直接上代码吧
- 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();
- }
- }
- }
- }
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的世界很精彩,期待您的参与。
忘记了,做个广告吧,为我的烂淘宝店,这是我开始尝试电商的一个通道,也希望能找到合适你用的东西。