//例子介绍:8266作为WiFiServer端,打开TCP调试助手,模拟TCP Client的请求 // 本机 ID 是 ESP_1C444B #include <SoftwareSerial.h> //实例化软串口 SoftwareSerial mySerial(D1, D2); // RX, TX #include <ESP8266WiFi.h> const int maxMsg =100; // 接收区缓存长度 const String HostName="ESP_1111"; const char* ssid = "yaoyao"; const char* password = "love123456"; #define MAX_SRV_CLIENTS 2 //做多多少个客户端可以连接 WiFiServer server(6666); //创建server 端口号是6666 WiFiClient serverClients[MAX_SRV_CLIENTS]; //定义最多多少个client可以连接本server(一般不要超过4个) void setup() { mySerial.begin(9600); //mySerial.println("Hello, world?"); Serial.begin(9600); //WiFi.hostname(HostName.c_str()); WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); Serial.print("\n连接到:"); Serial.println(ssid); uint8_t i = 0; while (WiFi.status() != WL_CONNECTED && i++ < 20) { delay(500); } if (i == 21) { Serial.print("没能连接到:"); Serial.println(ssid); return ; } server.begin(); //启动server server.setNoDelay(true);//关闭小包合并包功能,不会延时发送数据 Serial.print("设备已经联网 IP是: "); Serial.print(WiFi.localIP()); Serial.println(" 端口是: 6666"); Serial.println(" 设备名字:"); Serial.println( WiFi.hostname()); } /* wl_tcp_state 包括: CLOSED = 0,// 关闭 LISTEN = 1,// 监听中 SYN_SENT = 2, SYN_RCVD = 3, ESTABLISHED = 4,// 建立连接 FIN_WAIT_1 = 5, FIN_WAIT_2 = 6, CLOSE_WAIT = 7, CLOSING = 8, LAST_ACK = 9, TIME_WAIT = 10 */ void loop() { uint8_t i; //1 检测新链接 if (server.hasClient()) { //判断是否有新的client请求进来 Serial.print("测试新客户 "); for (i = 0; i < MAX_SRV_CLIENTS; i++) { //释放旧无效或者断开的client if (!serverClients[i] || !serverClients[i].connected()) { if (!serverClients[i]) { //serverClients[i] 判断指定序号的客户端是否有效 serverClients[i].stop(); //停止指定客户端的连接 } serverClients[i] = server.available();//分配最新的client Serial.print("1个新的客户端: "); Serial.println(i); break; //跳出一层for循环 } } //当达到最大连接数 无法释放无效的client,需要拒绝连接 if (i == MAX_SRV_CLIENTS) { WiFiClient client = server.available(); client.stop(); Serial.println("连接被拒绝 "); } } //2 检测client发过来的数据 for (i = 0; i < MAX_SRV_CLIENTS; i++) { if (serverClients[i] && serverClients[i].connected()) { if (serverClients[i].available()) { String line = serverClients[i].readStringUntil(';'); Serial.println(line); /* int ind=0; char RecMsg[maxMsg]; while (serverClients[i].available()) { RecMsg[ind]=serverClients[i].read(); if (ind<maxMsg){ ind++;} else{ Serial.println("缓存区域溢满"); Serial.println(String(RecMsg)); ind=0; } } Serial.println(String(RecMsg)); */ } } } //3接收串口数据 发送 if (Serial.available()){ //Serial.available() mySerial String comdata =Serial.readStringUntil(';'); //Serial.println(comdata); for (i = 0; i < MAX_SRV_CLIENTS; i++) { if (serverClients[i] && serverClients[i].connected()) { // char cArr[comdata.length() + 1]; //comdata.toCharArray(cArr,comdata.length() + 1); //serverClients[i].write(cArr, comdata.length() + 1);//向客户端发送数据 serverClients[i].println(comdata); delay(1); } } } }