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

esp32


#include <WiFi.h>

#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.");           // 打印至串口
    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.");
  }
}

android

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <TextView
        android:id="@+id/server_ip_kj"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:text="192.168.4.1" />

    <TextView
        android:id="@+id/server_port_kj"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:text="1122" />

    <Button
        android:id="@+id/connect_btn_kj"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:text="连接服务器" />

    <EditText
        android:id="@+id/send_data_kj"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:ems="10"
        android:inputType="text"
        android:text="Name" />

    <Button
        android:id="@+id/send_btn_kj"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:text="发送" />


</LinearLayout>
package com.example.esp32_tcp_client;

import androidx.appcompat.app.AppCompatActivity;

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

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;
    private Button connect_btn_kj,send_btn_kj;
    private EditText send_data_kj;
    private Socket socket;
    InputStream inputStream;
    OutputStream outputStream;
    @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);
//        连接服务器
        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");
                                RecvData();
                            }else{
                                //连接失败
                                Log.i("Connect","Fail");
                            }
                        } catch (IOException e) {
                            //连接失败
                            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();
                            byte[] tmp = new byte[msg.length +1];
                            for(int i=0;i<msg.length;i++){
                                tmp[i] = msg[i];
                            }
                            tmp[msg.length] = '\n';
                            outputStream.write(tmp);
                            Log.i("sendmsg","OK");
                        } catch (IOException e) {
                            Log.i("sendmsg","Fail");
                            throw new RuntimeException(e);
                        }
                    }
                }).start();
            }
        });
    }
//        接收消息
    private void RecvData(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                while(socket != null && socket.isConnected() == true){
                    byte[] recv_buff = new byte[255];
                    try {
                        int len = inputStream.read(recv_buff);
                        if(len != -1){
                            Log.i("RecvDataLength",String.valueOf(len)); // len是接收到的字符个数
                            Log.i("RecvData",new String(recv_buff));
                        }
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }).start();
    }
}
<uses-permission android:name="android.permission.INTERNET" />

相关推荐

  1. esp32服务器android客户tcp通讯

    2023-12-11 06:58:03       59 阅读
  2. QT TCP通讯客户服务

    2023-12-11 06:58:03       51 阅读
  3. C++ TCP 服务客户通信例子

    2023-12-11 06:58:03       35 阅读
  4. UE5 C++TCP服务器客户

    2023-12-11 06:58:03       52 阅读
  5. Python中TCP服务器客户简易实现

    2023-12-11 06:58:03       36 阅读
  6. Qt tcp通信客户+服务器一对一)

    2023-12-11 06:58:03       34 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-11 06:58:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-11 06:58:03       100 阅读
  3. 在Django里面运行非项目文件

    2023-12-11 06:58:03       82 阅读
  4. Python语言-面向对象

    2023-12-11 06:58:03       91 阅读

热门阅读

  1. rust宏(macro)详解

    2023-12-11 06:58:03       67 阅读
  2. MYSQL数据类型详解

    2023-12-11 06:58:03       61 阅读
  3. 数组 注意事项

    2023-12-11 06:58:03       49 阅读
  4. GraphSAGE

    GraphSAGE

    2023-12-11 06:58:03      51 阅读
  5. C/C++语言的安全编码规范

    2023-12-11 06:58:03       52 阅读
  6. 计算机视觉-机器学习-人工智能顶会 会议地址

    2023-12-11 06:58:03       49 阅读
  7. 【求职】外企德科-网易游戏测试面试记录

    2023-12-11 06:58:03       55 阅读
  8. git commit语义规范

    2023-12-11 06:58:03       54 阅读