程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> 來用C#在開源硬件Netduino上搞個httpserver吧

來用C#在開源硬件Netduino上搞個httpserver吧

編輯:C#入門知識

   在Netduino上做一個httpserver並不是一件困難的事情,你只需要花點時間而已。

創建一個新的netduino plus的應用,不過你需要確定你選擇的是netduino plus這個工程,那麼很快你就可以做出一個web服務應用了。

在你的Main函數裡,你可以先放下一下代碼:

[csharp]  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就行了,不必特立獨行,如果你還不是很能夠把握住的話,對麼?

[html] // 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地址。

[csharp] Thread.Sleep(5000); 

Thread.Sleep(5000);
接著我們需要將所獲得的ip地址通過debug的形式顯示出來,當然,這需要運行在你的vs2010的debug模式下,查看你的調試窗口的內容,debug.print會讓調試結果顯示出來,

否則你沒法去訪問你的板子,因為你不知道netduino從你家的路由器裡獲得了什麼地址。

[csharp]  // 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地址,並等待你的浏覽器訪問請求了

[csharp]  / 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已經監聽請求了,我們需要創建一個死循環,在那裡你講看到通過你的浏覽器進入的請求。

[csharp]  // listen for and process incoming requests  
while (true) 

// listen for and process incoming requests
while (true)
{
}在這個循環裡,你將獲得從客戶端訪問來的socket請求。

[csharp] // wait for a client to connect  
Socket clientSocket = listenerSocket.Accept(); 

// wait for a client to connect
Socket clientSocket = listenerSocket.Accept();然後,為了讓所有的請求數據都順利達到,你需要等待5秒的時間,


[csharp] // 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裡吧


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

byte[] buffer = new byte[clientSocket.Available];
int bytesRead = clientSocket.Receive(buffer);就快完了,知道你們都看膩了,下一步我們要分析請求的參數,並將板子上的led燈的狀態給修改過來。

[csharp] view plaincopyprint?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") + ".";


[csharp]  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關閉了吧。


[csharp] // important: close the client socket  
clientSocket.Close(); 

// important: close the client socket
clientSocket.Close();好了不來虛的,直接上代碼吧

[csharp]  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的世界很精彩,期待您的參與。

忘記了,做個廣告吧,為我的爛淘寶店,這是我開始嘗試電商的一個通道,也希望能找到合適你用的東西。

 

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved