如何用ESP8266创建TCP server? [英] how create TCP server by ESP8266?
问题描述
我想通过ESP8266在Arduino IDE中创建一个简单的Wifi TCP服务器.但是我有一个大问题:当我从客户端发送字符或字符串时,我无法在服务器上接收到它.
I want to create a simple Wifi TCP server by ESP8266 in Arduino IDE. But I have a big problem: when I send a character or string from client I can't receive it on the server.
实际上我将esp8266连接到我的PC,我想在PC终端中查看来自客户端的发送字符. 我的发送方是android的Socket协议应用!我在服务器端编写的完整代码是:
In fact I connect esp8266 to my PC and I want to see send character from client in pc terminal. my sending side is Socket protocol app for android!and complete code I write in sever side is:
WiFiServer server(8888);
void setup()
{
initHardware();
setupWiFi();
server.begin();
}
void loop()
{
WiFiClient client = server.available();
if (client) {
if (client.available() > 0) {
char c = client.read();
Serial.write(c);
}
}
}
void setupWiFi()
{
WiFi.mode(WIFI_AP);
WiFi.softAP("RControl", WiFiAPPSK);
}
void initHardware()
{
Serial.begin(115200);
}
将两侧波特率设置为115200.
Baudrate it set to 115200 on both sides.
推荐答案
在循环中,一旦建立客户端连接并删除WiFiClient
对象,您将关闭该客户端连接.
In the loop, you are closing the client connection as soon as it is established deleting the WiFiClient
object.
为了保持连接打开,您可以像这样修改循环:
In order to keep the connection open you could modify the loop like this :
WiFiClient client;
void loop()
{
if (!client.connected()) {
// try to connect to a new client
client = server.available();
} else {
// read data from the connected client
if (client.available() > 0) {
Serial.write(client.read());
}
}
}
未连接客户端时,它将尝试连接一个客户端;当连接客户端时,它将读取传入的数据.
When client is not connected it tries to connect one and when a client is connected, it reads incoming data.
这篇关于如何用ESP8266创建TCP server?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!