gpt4 book ai didi

Android通过套接字发送大文件

转载 作者:可可西里 更新时间:2023-11-01 02:31:43 24 4
gpt4 key购买 nike

目前我正在尝试为我的 Android 设备创建一个小套接字应用程序。

我想通过套接字连接将大文件 (~500MB) 发送到我的笔记本电脑/PC 或其他设备。我在我的 Android 设备上使用套接字客户端连接到我的 PC 上的套接字服务器,但是,当我尝试发送测试字段 (~460MB) 时,我的应用程序崩溃并显示:

"Throwing OutOfMemoryError "Failed to allocate a 441616290 byte allocationwith 4194304 free bytes and 90MB until OOM""

我想我的客户无法处理这个文件大小。所以我的问题是:有没有办法通过 TCP 套接字连接来处理如此大的文件?我的代码适用于小文件(例如 5MB),但适用于更大的文件。

这是我目前所拥有的:

在我的安卓设备上运行的客户端:

private class Connecting extends AsyncTask<String, Integer, String>
{
@Override
protected String doInBackground(String... serverAdd)
{
String filePath = "Path to file";

File sdFile = new File(filePath);

try {

client = new Socket("ip", "port");

outputStream = client.getOutputStream();
byte[] buffer = new byte[1024];
FileInputStream in = new FileInputStream(sdFile);
int rBytes;
while((rBytes = in.read(buffer, 0, 1024)) != -1)
{
outputStream.write(buffer, 0, rBytes);
}

outputStream.flush();
outputStream.close();
client.close();


} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

return null;
}
}

服务器端:

public class Main {

private static ServerSocket serverSocket;
private static Socket clientSocket;
private static InputStream inputStream;
private static FileOutputStream fileOutputStream;
private static BufferedOutputStream bufferedOutputStream;
private static int filesize = 10000000;
private static int bytesRead;
private static int current = 0;

public static void main(String[] args) throws IOException {

serverSocket = new ServerSocket(10898);

System.out.println("Server started. Listening to the port 10898");

clientSocket = serverSocket.accept();

byte[] mybytearray = new byte[filesize];

inputStream = clientSocket.getInputStream();
fileOutputStream = new FileOutputStream("E:\\output.zip");
bufferedOutputStream = new BufferedOutputStream(fileOutputStream);

System.out.println("Receiving...");

bytesRead = inputStream.read(mybytearray, 0, mybytearray.length);
current = bytesRead;

do {
bytesRead = inputStream.read(mybytearray, current, (mybytearray.length - current));
if (bytesRead >= 0) {
current += bytesRead;
}
} while (bytesRead > -1);


bufferedOutputStream.write(mybytearray, 0, current);
bufferedOutputStream.flush();
bufferedOutputStream.close();
inputStream.close();
clientSocket.close();
serverSocket.close();

System.out.println("Sever recieved the file");

}
}

问候

[编辑]:客户端代码。

最佳答案

这里是关于如何将文件分 block 的 Java 示例代码。您可以将此应用到您的 TCP/IP 客户端-服务器应用程序中。有关分 block 的更多信息,请参见此处 ( Java - Read file by chunks?),我从中获取了示例。

char[] myBuffer = new char[1024];
int bytesRead = 0;
BufferedReader in = new BufferedReader(new FileReader("foo.txt"));
while ((bytesRead = in.read(myBuffer, 0, 1024)) != -1)
{
...
}

关于Android通过套接字发送大文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31436072/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com