关于从 Android 设备接收文件到 esp8266 的问题

发布于 2025-01-18 16:42:39 字数 7852 浏览 1 评论 0 原文

我一直在研究一个项目,我将从我编写的 Android 应用程序发送一个文件到我的 esp8266;然后esp8266会将文件写入SD卡。但是当 esp 接收到文件(例如 .jpg)时,它都是乱码并且有噪音。 如果我收到 .txt 文件,无论我使用什么方法,它总是会在开头添加 (?? ur [B??óøTà xp ??) 。

这是我的安卓代码: (服务器线程)

Socket mySocket = null;
ServerSocket serverSocket = null;

class ServerThread implements Runnable{
    int serverPort;
    public ServerThread(int serverPort){
        this.serverPort = serverPort;
    }
    @Override
    public void run() {
        try {
            serverSocket = new ServerSocket(serverPort);
            mySocket = serverSocket.accept();
            output = new PrintWriter(mySocket.getOutputStream());
            input = new BufferedReader(new InputStreamReader(mySocket.getInputStream()));
            Log.i("connection", "server");

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    connection_state = true;
                    LinearLayout.LayoutParams textParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                    TextView thisText = new TextView(MainActivity.this);
                    thisText.setId(append);
                    thisText.setText("Server port: " + 8080 + " ... A client just made connection");
                    thisText.setTextSize(20);
                    thisText.setBackgroundColor(Color.rgb(25, 24, 24));
                    thisText.setTextColor(Color.rgb(0, 100, 0));
                    append++;
                    thisText.setGravity(20);
                    thisText.setLayoutParams(textParams);
                    myTexts.addView(thisText);
                }
            });
            new Thread(new ReceiveStringThread()).start();
        } catch (IOException e) {
            e.printStackTrace();
            Log.i("connection", "couldn't establish connection");
        } finally {
            try {
                if (socket != null)
                    socket.close();
                if (serverSocket != null)
                    serverSocket.close();

            }catch (IOException e){
               e.getStackTrace();
            }
        }
    }
}

发送文件线程:

class SendFileThread implements Runnable{
    String filePath;

    SendFileThread(String filePath) {
        this.filePath = filePath;
    }

    @Override
    public void run() {
        if(connection_state) {
            File findFile = new File(filePath);

            byte[] sendIt = new byte[(int) findFile.length()];

            try {
                BufferedInputStream bufferFile = new BufferedInputStream(new FileInputStream(findFile));

                bufferFile.read(sendIt, 0, sendIt.length);
                ObjectOutputStream oos = new ObjectOutputStream(mySocket.getOutputStream());
                oos.writeObject(sendIt);
                oos.flush();

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "File was sent successfully. size: " +
                                       (int) findFile.length() + " bytes", Toast.LENGTH_SHORT).show();
                    }
                });

            } catch (IOException e) {
                e.getStackTrace();
            }finally {
                try {
                    mySocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}

这是我的 esp8266 的 arduino 代码:

#include <ESP8266WiFi.h>
#include <SD.h>

#ifndef STASSID
#define STASSID "ESP_CLIENT"
#define STAPSK  "client-1234"
#endif

const char* ssid     = STASSID;
const char* password = STAPSK;

const char* host = "192.168.1.103";
const uint16_t port = 8080;

boolean connectionStatus = false;

byte buffer_array[10] = {'0x00', '0x00', '0x00', '0x00', '0x00', '0x00', '0x00', '0x00', '0x00', '0x00'};
int num_read;

WiFiClient client;

void setup() {
    Serial.begin(57600);

    //.................Initiate SD card................//
    if(!SD.begin(SS)){
        Serial.println("SD card initialization failed!");
        return;
    }else{
        Serial.println("SD card initialized successfully");
    }

    Serial.println();
    Serial.println();
    Serial.print("Connecting to ");
    Serial.println(ssid);

    WiFi.mode(WIFI_STA);
    WiFi.begin(ssid, password);

    while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
    }

    Serial.println("");
    Serial.println("WiFi connected");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
}

char *printBytes(byte *bytes) {
  char bytesStr[10];
  sprintf(bytesStr, "%02X", *bytes);
  Serial.print("byte: ");
  Serial.println(bytesStr);  

  return bytesStr;
}

void loop() {
    if(!connectionStatus){
        Serial.print("connecting to ");
        Serial.print(host);
        Serial.print(':');
        Serial.println(port);
        
        if (!client.connect(host, port)) {
            Serial.println("********************************************Connection failed************************************************");
            connectionStatus = false;
            delay(1000);
            return;
        }else{
            Serial.println("********************************************Connection established with server***********************************************");
            connectionStatus = true;
        }
        
        Serial.println("sending data to server");
        if (client.connected()) {
          client.println("hello from ESP8266");
        }
    }
    
    if(client.available()){
        Serial.println("Receiving...");
        num_read = client.readBytesUntil('\n',buffer_array, 10);
        Serial.println("bytes read: " + (String)num_read);
        printBytes(buffer_array);

        File appendSD = SD.open("/testESP32.txt", FILE_WRITE);
        if(!appendSD){
            Serial.println("not found");
            return;
        }else{
            Serial.println("Writing byte to file...");
            appendSD.write(buffer_array, num_read);
            appendSD.close();
        }
    }
}

无论我将它们放入哪种模式,无论是 esp 作为服务器,android 设备作为客户端还是反向,都不会产生任何影响全部。

有人知道如何解决这个问题吗?

我修改了 SendFileThread 如下,但它仅适用于正确发送 .txt 文件。但发送 .jpg 等图像文件问题仍然存在。

class SendFileThread implements Runnable{
    String filePath;

    SendFileThread(String filePath) {
        this.filePath = filePath;
    }

    @Override
    public void run() {
        if(connection_state) {
            File findFile = new File(filePath);

            byte[] sendIt = new byte[(int) findFile.length()];

            try {
                BufferedInputStream bufferFile = new BufferedInputStream(new FileInputStream(findFile));

                bufferFile.read(sendIt, 0, sendIt.length);
                OutputStream os= mySocket.getOutputStream();
                os.write(sendIt);
                os.flush();

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "File was sent successfully. size: " +
                                       (int) findFile.length() + " bytes", Toast.LENGTH_SHORT).show();
                    }
                });

            } catch (IOException e) {
                e.getStackTrace();
            }finally {
                try {
                    mySocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }else{

        }
    }
}

我希望能够发送各种数据,如 .pdf .doxs 以及 ObjectOutputStream 发送所有这些类型的文件就好了,如果我将它们发送到另一部 Android 手机而不是 esp8266

I've been working on a project where i would send a file from the android app i wrote to my esp8266; the esp8266 then will write the file onto the SD card. but when esp receives the file for example a .jpg, it's all garbled and noisy.
and if i receive a .txt file it will always add a (¬í ur [B¬óøTà xp ¬) at the beginning, regardless of what method i use.

Here's my android code:
(Server thread)

Socket mySocket = null;
ServerSocket serverSocket = null;

class ServerThread implements Runnable{
    int serverPort;
    public ServerThread(int serverPort){
        this.serverPort = serverPort;
    }
    @Override
    public void run() {
        try {
            serverSocket = new ServerSocket(serverPort);
            mySocket = serverSocket.accept();
            output = new PrintWriter(mySocket.getOutputStream());
            input = new BufferedReader(new InputStreamReader(mySocket.getInputStream()));
            Log.i("connection", "server");

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    connection_state = true;
                    LinearLayout.LayoutParams textParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                    TextView thisText = new TextView(MainActivity.this);
                    thisText.setId(append);
                    thisText.setText("Server port: " + 8080 + " ... A client just made connection");
                    thisText.setTextSize(20);
                    thisText.setBackgroundColor(Color.rgb(25, 24, 24));
                    thisText.setTextColor(Color.rgb(0, 100, 0));
                    append++;
                    thisText.setGravity(20);
                    thisText.setLayoutParams(textParams);
                    myTexts.addView(thisText);
                }
            });
            new Thread(new ReceiveStringThread()).start();
        } catch (IOException e) {
            e.printStackTrace();
            Log.i("connection", "couldn't establish connection");
        } finally {
            try {
                if (socket != null)
                    socket.close();
                if (serverSocket != null)
                    serverSocket.close();

            }catch (IOException e){
               e.getStackTrace();
            }
        }
    }
}

Send file thread:

class SendFileThread implements Runnable{
    String filePath;

    SendFileThread(String filePath) {
        this.filePath = filePath;
    }

    @Override
    public void run() {
        if(connection_state) {
            File findFile = new File(filePath);

            byte[] sendIt = new byte[(int) findFile.length()];

            try {
                BufferedInputStream bufferFile = new BufferedInputStream(new FileInputStream(findFile));

                bufferFile.read(sendIt, 0, sendIt.length);
                ObjectOutputStream oos = new ObjectOutputStream(mySocket.getOutputStream());
                oos.writeObject(sendIt);
                oos.flush();

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "File was sent successfully. size: " +
                                       (int) findFile.length() + " bytes", Toast.LENGTH_SHORT).show();
                    }
                });

            } catch (IOException e) {
                e.getStackTrace();
            }finally {
                try {
                    mySocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}

and here's my arduino code for esp8266:

#include <ESP8266WiFi.h>
#include <SD.h>

#ifndef STASSID
#define STASSID "ESP_CLIENT"
#define STAPSK  "client-1234"
#endif

const char* ssid     = STASSID;
const char* password = STAPSK;

const char* host = "192.168.1.103";
const uint16_t port = 8080;

boolean connectionStatus = false;

byte buffer_array[10] = {'0x00', '0x00', '0x00', '0x00', '0x00', '0x00', '0x00', '0x00', '0x00', '0x00'};
int num_read;

WiFiClient client;

void setup() {
    Serial.begin(57600);

    //.................Initiate SD card................//
    if(!SD.begin(SS)){
        Serial.println("SD card initialization failed!");
        return;
    }else{
        Serial.println("SD card initialized successfully");
    }

    Serial.println();
    Serial.println();
    Serial.print("Connecting to ");
    Serial.println(ssid);

    WiFi.mode(WIFI_STA);
    WiFi.begin(ssid, password);

    while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
    }

    Serial.println("");
    Serial.println("WiFi connected");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
}

char *printBytes(byte *bytes) {
  char bytesStr[10];
  sprintf(bytesStr, "%02X", *bytes);
  Serial.print("byte: ");
  Serial.println(bytesStr);  

  return bytesStr;
}

void loop() {
    if(!connectionStatus){
        Serial.print("connecting to ");
        Serial.print(host);
        Serial.print(':');
        Serial.println(port);
        
        if (!client.connect(host, port)) {
            Serial.println("********************************************Connection failed************************************************");
            connectionStatus = false;
            delay(1000);
            return;
        }else{
            Serial.println("********************************************Connection established with server***********************************************");
            connectionStatus = true;
        }
        
        Serial.println("sending data to server");
        if (client.connected()) {
          client.println("hello from ESP8266");
        }
    }
    
    if(client.available()){
        Serial.println("Receiving...");
        num_read = client.readBytesUntil('\n',buffer_array, 10);
        Serial.println("bytes read: " + (String)num_read);
        printBytes(buffer_array);

        File appendSD = SD.open("/testESP32.txt", FILE_WRITE);
        if(!appendSD){
            Serial.println("not found");
            return;
        }else{
            Serial.println("Writing byte to file...");
            appendSD.write(buffer_array, num_read);
            appendSD.close();
        }
    }
}

and regardless of which mode i put them into, whether it'll be esp as server and android device as client or reverse, it won't make a difference at all.

anyone knows how to fix this?

i modified the SendFileThread as below but it only worked for sending .txt files correctly. but sending image files like .jpg problem still stands.

class SendFileThread implements Runnable{
    String filePath;

    SendFileThread(String filePath) {
        this.filePath = filePath;
    }

    @Override
    public void run() {
        if(connection_state) {
            File findFile = new File(filePath);

            byte[] sendIt = new byte[(int) findFile.length()];

            try {
                BufferedInputStream bufferFile = new BufferedInputStream(new FileInputStream(findFile));

                bufferFile.read(sendIt, 0, sendIt.length);
                OutputStream os= mySocket.getOutputStream();
                os.write(sendIt);
                os.flush();

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "File was sent successfully. size: " +
                                       (int) findFile.length() + " bytes", Toast.LENGTH_SHORT).show();
                    }
                });

            } catch (IOException e) {
                e.getStackTrace();
            }finally {
                try {
                    mySocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }else{

        }
    }
}

and i wanna be able to send all kinds of data like .pdf .doxs as well and ObjectOutputStream sends all this kinds of files just fine if although i'm sending them to another android phone not esp8266

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

归途 2025-01-25 16:42:39

已解决:我使用了

client.read(buffer_array,10);

对于图像文件而不是

client.readBytesUntil('\n', buffer_array, 10);

在Android中更改

ObjectOutputStream oos = new ObjectOutputStream(mySocket.getOutputStream());
        oos.writeObject(sendIt);

OutputStream os= mySocket.getOutputStream();
            os.write(sendIt);

,它最终适用于所有类型的文件!

SOLVED: i used

client.read(buffer_array, 10);

for image files instead of

client.readBytesUntil('\n', buffer_array, 10);

and in android changed

ObjectOutputStream oos = new ObjectOutputStream(mySocket.getOutputStream());
        oos.writeObject(sendIt);

to

OutputStream os= mySocket.getOutputStream();
            os.write(sendIt);

and it finally worked for all types of files!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文