[英]Recieve Data from ESP32 Socket Server with Android
I'm trying to recieve data from my ESP32 with an Android App.我正在尝试使用 Android 应用程序从我的 ESP32 接收数据。 Sending data from my phone isn't a problem.从我的手机发送数据不是问题。 I just don't get anything.我只是什么都得不到。 It doesn't show an exception and also not a msg.它没有显示异常,也没有显示消息。 My code so far:到目前为止我的代码:
//In the onCreate method:
Connection connection = new Connection();
connection.execute();
//The Connection:
class Connection extends AsyncTask<Void,Void,Void> {
String msg;
@Override
protected Void doInBackground(Void...params){
try{
client = new Socket("ESP32-1",80);
input = new BufferedReader(new InputStreamReader(client.getInputStream()));
System.out.println(input.readLine());
}catch (UnknownHostException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
while (true) {
try {
msg=input.readLine();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(msg);
}
}
}
Permissions:权限:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
ESP32(in Arduino IDE): ESP32(在 Arduino IDE 中):
#include <WiFi.h>
const char* ssid="Jack-2.4";
const char* password="QayWsxEdcRfv123456#";
WiFiServer server(80);
void setup() {
//Server
Serial.begin(115200);
Serial.println("start");
delay(1000);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi..");
}
Serial.println("Connected to the WiFi network");
Serial.println(WiFi.localIP());
server.begin();
}
void loop() {
WiFiClient client = server.available();
if (client) {
Serial.println("Client connected");
while (client.connected()) {
client.write('A');
delay(500);
}
}
}
I checked the ESP32 Code if it writes and it does send the messages.我检查了 ESP32 代码是否写入并且它确实发送了消息。 Is there anything i missed?有什么我想念的吗?
Your Android code is calling input.readLine()
but your ESP32 code is only sending a single character, not a line, so of course the client never shows any input.您的 Android 代码正在调用input.readLine()
但您的 ESP32 代码只发送一个字符,而不是一行,因此客户端当然不会显示任何输入。 Try sending a line.尝试发送一条线路。
client.writeln('A');
or或者
client.write("A\n");
The string in the second version might need to be "A\r\n"
;第二个版本中的字符串可能需要是"A\r\n"
; I'm not 100% clear what Android will consider to be a line terminator.我不是 100% 清楚 Android 会认为什么是行终止符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.