博客
关于我
wemos D1 arduino物联网开发板应用笔记7-STA模式下TCP Client通信
阅读量:601 次
发布时间:2019-03-12

本文共 1431 字,大约阅读时间需要 4 分钟。

WeMos D1STA模式下TCP客户端通信实现

模块连接AP

路由器名字:lxy2305,密码:123456789a

代码示例:

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

Socket套接字实现TCP Client流程

Socket套接字用于TCP客户端通信,流程如下:

  • 连接AP并获取局域网IP
  • 使用WiFiClient库进行TCP通信
  • WiFiClient库简介

    WiFiClient库简化了Wemos D1的TCP通信开发流程,主要包含连接、通信、获取状态三类API。其功能包括:

    • 连接服务器
    • 发送数据
    • 接收数据
    • 获取连接状态

    实例代码

    #include 
    char* ssid = "lxy2305"; char* passwd = "123456789a"; const uint16_t port = 8089; const char* host = "192.168.1.7"; WiFiClient client; void setup() { Serial.begin(115200); WiFi.mode(WIFI_STA); WiFi.begin(ssid, passwd); while (WiFi.status() != WL_CONNECTED) { Serial.print("."); delay(500); } Serial.println("WiFi connected, local IP address:"); Serial.println(WiFi.localIP()); delay(500); if (!client.connect(host, port)) { Serial.println("connection failed"); delay(5000); } else { Serial.println("connect to tcp server success."); client.println(String("hello tcp server")); } } void loop() { String recv_data = client.readStringUntil('\r'); Serial.println(recv_data); if (recv_data.compareTo("exit") == 0) { Serial.println("closing connection"); client.stop(); } delay(200); }

    运行步骤

  • 获取电脑IP地址

    • 在CMD控制台输入ipconfig获取当前IP地址
  • 使用网络助手创建TCP Server

    • 设置端口为8089
  • 下载运行

    • 上传代码到WeMos D1,查看串口输出
  • 结语

    注意事项:

    • 确保网络助手设置正确
    • 端口号可自定义
    • 代码获取及使用支持

    如有问题,可加入QQ交流群(906015840)或关注公众号“物联网客栈”。

    转载地址:http://aahtz.baihongyu.com/

    你可能感兴趣的文章
    notepad如何自动对齐_notepad++怎么自动排版
    查看>>
    Notes on Paul Irish's "Things I learned from the jQuery source" casts
    查看>>
    Notification 使用详解(很全
    查看>>
    NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
    查看>>
    NotImplementedError: Could not run torchvision::nms
    查看>>
    nova基于ubs机制扩展scheduler-filter
    查看>>
    Now trying to drop the old temporary tablespace, the session hangs.
    查看>>
    nowcoder—Beauty of Trees
    查看>>
    np.arange()和np.linspace()绘制logistic回归图像时得到不同的结果?
    查看>>
    np.power的使用
    查看>>
    NPM 2FA双重认证的设置方法
    查看>>
    npm build报错Cannot find module ‘webpack/lib/rules/BasicEffectRulePlugin‘解决方法
    查看>>
    npm build报错Cannot find module ‘webpack‘解决方法
    查看>>
    npm ERR! ERESOLVE could not resolve报错
    查看>>
    npm ERR! fatal: unable to connect to github.com:
    查看>>
    npm ERR! Unexpected end of JSON input while parsing near '...on":"0.10.3","direc to'
    查看>>
    npm ERR! Unexpected end of JSON input while parsing near ‘...“:“^1.2.0“,“vue-html-‘ npm ERR! A comp
    查看>>
    npm error Missing script: “server“npm errornpm error Did you mean this?npm error npm run serve
    查看>>
    npm error MSB3428: 未能加载 Visual C++ 组件“VCBuild.exe”。要解决此问题,1) 安装
    查看>>
    npm install CERT_HAS_EXPIRED解决方法
    查看>>