esp32服务器与android客户端的tcp通讯

esp32

//esp32作为服务端
#include 

#define LED_BUILTIN 2 
// 创建热点
const char *ssid = "ESP32";
const char *password = "12345678";
const int port = 1122; //端口
WiFiServer server(port);
void setup() {
  delay(5000);
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);
  Serial.begin(115200);
  Serial.println();
  Serial.println("Configuring access point...");
  // You can remove the password parameter if you want the AP to be open.
  WiFi.softAP(ssid, password);
  IPAddress myIP = WiFi.softAPIP();
  Serial.print("AP IP address: ");
  Serial.print(myIP);
  Serial.print(":");
  Serial.println(port);
  server.begin();
  Serial.println("Server started!");
}

void loop() {
  WiFiClient client = server.available();   // 监听新客户端
  if (client) {     
    digitalWrite(LED_BUILTIN, HIGH);                        // 如果有客户端接入
    Serial.println("New Client In.");           // 打印至串口
    String currentLine = "";                // 用来保存客户端发来的数据  一段指令以换行符结尾
    while (client.connected()) {            // 当有持续连接时循环
      if (client.available()) {             // 如果有信息待接收
        char c = client.read();             // read a byte, then  判断字符是不是\n  从而判断有没有结束
        // Serial.write(c);                    // 串口打印
        if(c != '\n'){   //一段指令以换行符结尾
          currentLine += c;
        }else{
          Serial.println(currentLine);
          client.print(currentLine); //返回数据到客户端
          currentLine = ""; 
        }
      }
    }
    // close the connection:
    client.stop();
    digitalWrite(LED_BUILTIN, LOW);   
    Serial.println("Client Disconnected.");
  }
}
//esp32 tcp客户端
#include 
#include 
 
const char *ssid = "Netcore_dsx";
const char *password = "dsx54254";
const IPAddress serverIP(192,168,0,3); //欲访问的地址
uint16_t serverPort = 1122;         //服务器端口号

WiFiClient client; //声明一个客户端对象,用于与服务器进行连接
 
//初始化wifi
void wifi_init()
{
    WiFi.mode(WIFI_STA);
    WiFi.setSleep(false); //关闭STA模式下wifi休眠,提高响应速度
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED)
    {
        delay(500);
        Serial.println(".");
    }
    Serial.println("IP Address:");
    Serial.println(WiFi.localIP());
}
 
void setup()
{
  Serial.begin(115200);
  wifi_init();
}
 
void loop()
{
  if (client.connect(serverIP, serverPort)) //尝试访问目标地址
  {
     client.println("Hello Server,I Am ESP32!");
     while (client.connected() || client.available()) //如果已连接或有收到的未读取的数据
     {
        if (client.available()) //如果tcp网络有数据可读取 读取网络数据
        {
          String line = client.readStringUntil('\n'); //读取数据到换行符
          Serial.println(line);
          client.print(line);
          // 如果数据是服务器发送给esp32的 则通过串口发给esp32
          // if (line.substring(0,esp32_head.length()) == esp32_head)
          // {
          //     Serial.println(line);
          // }
        }
    }
  }
  else
  {
      Serial.println("Connect To Tcp Server Failed!After 10 Seconds Try Again!");
      client.stop(); //关闭客户端
  }
  delay(10000);
}

android客户端




    

    

    
package com.example.esp32_tcp_client;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private TextView server_ip_kj,server_port_kj,recv_data_kj;
    private Button connect_btn_kj,send_btn_kj;
    private EditText send_data_kj;
    private Socket socket;
    InputStream inputStream;
    OutputStream outputStream;
    MyHandle myHandle;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        server_ip_kj = findViewById(R.id.server_ip_kj);
        server_port_kj = findViewById(R.id.server_port_kj);
        connect_btn_kj = findViewById(R.id.connect_btn_kj);
        send_btn_kj = findViewById(R.id.send_btn_kj);
        send_data_kj = findViewById(R.id.send_data_kj);
        recv_data_kj = findViewById(R.id.recv_data_kj);
        myHandle = new MyHandle();
//        连接服务器
        connect_btn_kj.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            socket = new Socket(server_ip_kj.getText().toString(),Integer.valueOf(server_port_kj.getText().toString()));
                            if(socket.isConnected()){
                                //连接成功
                                outputStream = socket.getOutputStream();
                                inputStream = socket.getInputStream();
                                Log.i("Connect","OK");
                                Message msg = new Message();
                                msg.what = 0;
                                msg.obj = "连接服务器成功!";
                                myHandle.sendMessage(msg);
                                RecvData();
                            }else{
                                Message msg = new Message();
                                msg.what = 1;
                                msg.obj = "连接服务器失败!";
                                myHandle.sendMessage(msg);
                                //连接失败
                                Log.i("Connect","Fail");
                            }
                        } catch (IOException e) {
                            //连接失败
                            Message msg = new Message();
                            msg.what = 1;
                            msg.obj = "连接服务器失败!";
                            myHandle.sendMessage(msg);
                            Log.i("Connect","Fail");
                            throw new RuntimeException(e);
                        }
                    }
                }).start();
            }
        });
//        发送信息
        send_btn_kj.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            //向byte数组msg的最后添加'\n'
                            byte[] msg = send_data_kj.getText().toString().getBytes();
//                            msg数组的最后添加'\n'结束标志 存在tmp数组中
                            byte[] tmp = new byte[msg.length +1];
                            for(int i=0;i

你可能感兴趣的:(ESP32,Android,服务器,android,tcp/ip,ESP32)