使用c#连接NodeMCU服务器

本文关键字:服务器 NodeMCU 连接 使用 | 更新日期: 2023-09-27 18:16:30

我有一个带有ESP8266E芯片的NodeMCU 0.9板。我可以打开和关闭一个LED使用简单的代码下面。此代码使用Arduino IDE编写。

            #include <ESP8266WiFi.h>
            const char* ssid = "iPhone";
            const char* password = "1234567890ABCD";
            int ledPin = D0; // GPIO16
            WiFiServer server(80);
            void setup() {
              Serial.begin(9600);
              delay(10);
              pinMode(ledPin, OUTPUT);
              digitalWrite(ledPin, LOW);
              // Connect to WiFi network
              Serial.println();
              Serial.println();
              Serial.print("Connecting to ");
              Serial.println(ssid);
              WiFi.begin(ssid, password);
              while (WiFi.status() != WL_CONNECTED) {
                delay(500);
                Serial.print(".");
              }
              Serial.println("");
              Serial.println("WiFi connected");
              // Start the server
              server.begin();
              Serial.println("Server started");
              // Print the IP address
              Serial.print("Use this URL to connect: ");
              Serial.print("http://");
              Serial.print(WiFi.localIP());
              Serial.println("/");
            }
            void loop() {
              // Check if a client has connected
              WiFiClient client = server.available();
              if (!client) {
                return;
              }
              // Wait until the client sends some data
              Serial.println("new client");
              while(!client.available()){
                delay(1);
              }
              // Read the first line of the request
              //String request = client.readStringUntil(''r');
              String request = client.readString();
              Serial.println(request);
              client.flush();
              // Match the request
              int value = LOW;
              if (request.indexOf("/LED=ON") != -1)  {
                digitalWrite(ledPin, LOW);
                value = LOW;
              }
              if (request.indexOf("/LED=OFF") != -1)  {
                digitalWrite(ledPin, HIGH);
                value = HIGH;
              }
            // Set ledPin according to the request
            //digitalWrite(ledPin, value);
              // Return the response
              client.println("HTTP/1.1 200 OK");
              client.println("Content-Type: text/html");
              client.println(""); //  do not forget this one
              client.println("<!DOCTYPE HTML>");
              client.println("<html>");
              client.print("Led pin is now: ");
              if(value == LOW) {
                client.print("On");
              } else {
                client.print("Off");
              }
              client.println("<br><br>");
              client.println("<a href='"/LED=ON'"'"><button>Turn On </button></a>");
              client.println("<a href='"/LED=OFF'"'"><button>Turn Off </button></a><br />");  
              client.println("</html>");
              delay(1);
              Serial.println("Client disonnected");
              Serial.println("");
            }

然后我可以使用我的web浏览器连接到NodeMCU并打开和关闭LED。NodeMCU还将LED状态数据发送给浏览器。但是,我想使用c#表单应用程序来实现。我尝试了这个代码。在Visual Studio 2013中没有出现任何编译错误。但是,它无法连接到NodeMCU服务器。

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using System.Net.Sockets;
    using System.Net;

    namespace WindowsFormsApplication1
    {
        public partial class Form1 : Form
        {
            static TcpClient tcpClient = new TcpClient();
            public static readonly byte[] ip = new byte[] { 172, 20, 10, 2 };
            static IPAddress ipAddress = new IPAddress(ip);
            IPEndPoint hostEndPoint = new IPEndPoint(ipAddress, 80);
            static Socket soc = new Socket(AddressFamily.InterNetwork,  SocketType.Stream, ProtocolType.IP);
            ASCIIEncoding asen = new ASCIIEncoding();

            public Form1()
            {
                InitializeComponent();
            }

            private void button2_Click(object sender, EventArgs e)
            {
                soc.Connect(ipAddress, 80);
                NetworkStream stm = new NetworkStream(soc);
                tcpClient.Connect(ipAddress, 80);
                stm = tcpClient.GetStream();
                byte[] ba = asen.GetBytes("/LED=ON/r");
                stm.Write(ba,0,ba.Length);
            }
            private void button3_Click(object sender, EventArgs e)
            {
                soc.Connect(ipAddress, 80);
                NetworkStream stm = new NetworkStream(soc);
                tcpClient.Connect(ipAddress, 80);
                stm = tcpClient.GetStream();
                byte[] ba = asen.GetBytes("/LED=OFF/r");
                stm.Write(ba, 0, ba.Length);
            }
        }
    }

帮助我在c#中实现一个代码

使用c#连接NodeMCU服务器

虽然您可以使用低级api发出HTTP请求,但使用HttpClient类会更好:https://msdn.microsoft.com/en-us/library/system.net.http.httpclient(v=vs.110).aspx

下面是button2事件处理程序的一个简单示例:
private async void button2_Click(object sender, EventArgs e)
{
    using (var client = new HttpClient())
    {
        HttpResponseMessage request = await client.GetAsync("http://172.16.20.10/LED=on");
    }
}