参考:linux做一个客户端与WemosD1作为服务器的无线通信(局域网通信)
作者:枕上
发布时间:2021-07-19 23:33:44
网址:https://blog.csdn.net/jinchi_boke/article/details/118916896?utm_source=app&app_version=4.11.0&code=app_1562916241&uLinkId=usr1mkqgl919blen
目录
- client.c
- wemosD1(arduino平台编写服务器代码)
Linux作为客户端与wemosD1作为服务器进行网络通信:
需要的是:linux下的socket网络编程,为 linux 编写客户端
arduino平台为wemosD1,作为设备接入wifi,并架设Wemos为ftp服务器
wemosD1 WIFI模块代码demo:
https://blog.csdn.net/jinchi_boke/article/details/118915142
client.c
#include<netinet/in.h>
#include <arpa/inet.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>int main(int argc,char **argv){char readbuf[8] = {'\0'};struct sockaddr_in addr;memset(&addr,0,sizeof(struct sockaddr_in));if (argc!=3){printf("The input parameter is wrong\n");exit(-1);}//1.创建套接字int s_fd=socket(AF_INET, SOCK_STREAM,0); if (s_fd==-1){perror("socket");exit(-1);}addr.sin_family=AF_INET;addr.sin_port=htons(atoi(argv[2]));inet_aton(argv[1],&addr.sin_addr);//2.连接服务器if(connect(s_fd,(struct sockaddr *)&addr,sizeof(struct sockaddr))==-1) //连接wemosD1{perror("connect");exit(-1);}printf("connect....\n");while(1){printf("请输入发送的指令\n");gets(readbuf); //用这个编译有警告//fgets(readbuf,sizeof(readbuf),stdin); //puts(readbuf); write(s_fd,readbuf,strlen(readbuf)); //向wemosD1发送信息}return 0;
}
wemosD1(arduino平台编写服务器代码)
#include <ESP8266WiFi.h> //使用wifi的头文件char* ssid = "iPhone"; //“wifi热点名称”
char* passwd = "1234569870-1"; //”wifi热点密码”int port = 8888; //端口号
WiFiServer server(port); // 设置服务器端口号void initWifiSta()
{WiFi.mode(WIFI_STA); // 设置STA模式WiFi.begin(ssid, passwd); //连接网络while (WiFi.status() != WL_CONNECTED) {Serial.print(".");delay(500);} Serial.println(WiFi.localIP()); //通过串口打印wemos的IP地址
}void setup()
{Serial.begin(115200);initWifiSta();server.begin(); //启动服务器
}void loop()
{//Serial.println(WiFi.localIP()); //通过串口打印wemos的IP地址// delay(500);char cmd;WiFiClient client = server.available(); //服务初始化出一个客户端while (client.connected()) { //等待客户端连接while (client.available() > 0) { //有数据到来,类似串口的那个函数cmd = client.read();//读取数据if( cmd == '1'){Serial.println("just do it");}else{Serial.println("nothing"); }}
}}