博客
关于我
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/

    你可能感兴趣的文章
    Python web自动化测试 —— 文件上传
    查看>>
    Python web自动化测试 —— 文件上传!
    查看>>
    Python Web自动化测试开发环境搭建(附安装包与虚拟机环境)
    查看>>
    python win32api键盘_Python win32api.keybd_event模拟键盘输入
    查看>>
    python Windows显示当前鼠标坐标
    查看>>
    python Workbook 表格宽度
    查看>>
    python write报错a byte-like object is required.not str
    查看>>
    python yaml.dump 缩进错误
    查看>>
    Python yield generator
    查看>>
    python | authlib,一个强大的 Python 库!
    查看>>
    python | awswrangler,一个高效的 Python 库!
    查看>>
    python | bashplotlib,一个有趣的Python库!
    查看>>
    python | bentoml,一个超级厉害的 模型部署 Python 库!
    查看>>
    python调用jar包的模块_python调用jar包
    查看>>
    python | black,一个神奇的 代码格式化工具 Python 库!
    查看>>
    python | cartopy,一个有趣的 Python 库!
    查看>>
    python | cloud-init,一个实用的 云计算 Python 库!
    查看>>
    python | code2flow,一个神奇的 Python 库!
    查看>>
    python | cudf,一个超实用的 Python 库!
    查看>>
    python | daphne,一个非常nice的 Python 库!
    查看>>