nodemcu连接服务端双向传输数据arduino

nodemcu接收服务器数据,收到“1”,则点亮小灯,其他信息,则关闭小灯

0脚接小灯

16脚接3v3脚,这里模拟开关,当开关接通,则向服务器传送“开机”信息,如果断开,则发送“关机信息”

 


#include <ESP8266WiFi.h>

#ifndef STASSID
#define STASSID ""                    //wifi的账号
#define STAPSK  ""            //wifi的密码
#endif

const char* ssid     = STASSID;
const char* password = STAPSK;

const char* host = "192.168.8.10";        //tcp连接的服务器地址
const uint16_t port = 16550;              //服务器端口号
WiFiClient client;

String str="";                            //tcp接收的字符串


int status=0;                            //读取当前开机关机信号

void setup() {

  pinMode(0, OUTPUT);

  pinMode(16, OUTPUT);
  
  Serial.begin(115200);

  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);


  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void loop() {




  while (!client.connected())//若未连接到服务端,则客户端进行连接。
    {
        if (!client.connect(host, port))//实际上这一步就在连接服务端,如果连接上,该函数返回true
        {
            Serial.println("connection....");
            delay(500);

        }
    }

    str="";
    
    while (client.available())//available()表示是否可以获取到数据
    {
     
      str+=char(client.read());
      

      if(str.indexOf('\n')>0)
      {
          Serial.print(str);
        
          if(str=="1\n")
          {
            
    
            digitalWrite(0, HIGH);        //点亮小灯
          }
          else
          {
    
            
            digitalWrite(0, LOW);        //关闭小灯
          }
      }

    }

    if(digitalRead(16)==HIGH){
      if(status==0){
          client.println("开机");        //如果16脚与3v3通路,则向服务器发送开机
          status=1;
          delay(1000);
        }
      }
      else{
        
        if(status==1){
          client.println("关机");
          status=0;
          delay(1000);
          }
        }
}

 

 

服务端代码

 

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;
using System.Threading;
using System.Net.Sockets;

namespace TcpServer
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            //在多线程编程中,如果子线程需要使用主线程中创建的对象
            CheckForIllegalCrossThreadCalls = false;
        }

        Dictionary<string, Socket> clientList = new Dictionary<string, Socket>();


        private void Setserver()
        {
            //1.创建服务器端电话
            Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
            //2.创建手机卡
            IPAddress iP = IPAddress.Parse(textBox1.Text);
            IPEndPoint endPoint = new IPEndPoint(iP, int.Parse(textBox2.Text));
            //3.将电话卡插入到电话中
            server.Bind(endPoint);
            //4.开始监听电话
            //同一时刻允许同时加入链接的最大数量
            server.Listen(20);

            textBox3.Text = "服务器已经成功开启!\r\n" + textBox3.Text;

            //5.等待来电接电话
            while (true)
            {
                //接受接入的一个客户端
                connectClient = server.Accept();
                if (connectClient != null)
                {
                    
                    string info = connectClient.RemoteEndPoint.ToString();
                    clientList.Add(info, connectClient);
                    

                    textBox3.Text = info + "加入服务器!\r\n" + textBox3.Text;
                    string msg = DateTime.Now + "你已经成功进入聊天室!";
                    //SendMsg(msg);
                    //每有一个客户端接入,需要有一个线程进行服务
                    Thread threadclient = new Thread(ReciveMsg);
                    threadclient.IsBackground = true;
                    //设置这个线程中的通信对象时对应的socket与客户端socket进行通信
                    threadclient.Start(connectClient);
                }
            }
        }
        void ReciveMsg(object o)
        {
            Socket client = o as Socket;
            while (true)
            {
                try
                {
                    byte[] arrMsg = new byte[1024 * 1024];
                    int length = client.Receive(arrMsg);
                    if (length > 0)
                    {
                        string recMsg = Encoding.UTF8.GetString(arrMsg, 0, length);
                        IPEndPoint endPoint = client.RemoteEndPoint as IPEndPoint;


                        textBox3.Text += DateTime.Now + "[" + endPoint.Port.ToString() + "]" + recMsg;
                        //SendMsg("[" + endPoint.Port.ToString() + "]" + recMsg);
                    }
                }
                catch (Exception)
                {
                    try
                    {
                        client.Close();
                        clientList.Remove(client.RemoteEndPoint.ToString());
                    }
                    catch
                    { }
                }
            }
        }
        Socket connectClient;
        void SendMsg(string str)
        {


            foreach (var item in clientList)
            {

                byte[] arrMsg = Encoding.UTF8.GetBytes(str + "\n");

                try
                {
                    int x = item.Value.Send(arrMsg);
                    label3.Text = x.ToString();
                }
                catch (Exception ex)
                {
                    label3.Text += ex.Message.ToString();
                }

            }

            //byte[] arrMsg = Encoding.UTF8.GetBytes(str);
            //clientList["192.168.6.101:53321"].Send(arrMsg);
        }


        private void button1_Click(object sender, EventArgs e)
        {
            Thread thread = new Thread(Setserver);
            thread.IsBackground = true;
            thread.Start();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            label3.Text = "";

            if (textBox4.Text != null)
            {

                //SendMsg(DateTime.Now + textBox4.Text);


                SendMsg(textBox4.Text);
                textBox4.Text = "";
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}

 

  • 0
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

糖朝

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值