esp32服务器与android客户端的tcp通讯
2023-12-14 05:36:26
esp32
//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 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 <Arduino.h>
#include <WiFi.h>
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客户端
<?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="连接服务器" />
<TextView
android:id="@+id/recv_data_kj"
android:layout_width="match_parent"
android:layout_height="200dp"
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.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<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){
byte[] tmp = new byte[len];
System.arraycopy(recv_buff,0,tmp,0,len);
Log.i("RecvDataLength",String.valueOf(len)); // len是接收到的字符个数
Log.i("RecvData",new String(tmp));
Message msg = new Message();
msg.what = 2;
msg.obj = new String(tmp);
myHandle.sendMessage(msg);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}).start();
}
public class MyHandle extends Handler
{
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
switch (msg.what){
case 0:
Toast.makeText(MainActivity.this,msg.obj.toString(),Toast.LENGTH_SHORT).show();
break;
case 1:
Toast.makeText(MainActivity.this,msg.obj.toString(),Toast.LENGTH_SHORT).show();
break;
case 2:
recv_data_kj.setText(msg.obj.toString());
Toast.makeText(MainActivity.this,msg.obj.toString(),Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
}
protected void onDestroy(){
super.onDestroy();
try {
socket.close();
inputStream.close();
outputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
<uses-permission android:name="android.permission.INTERNET" />
文章来源:https://blog.csdn.net/weixin_42854045/article/details/134913068
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!