gpt4 book ai didi

Android Java TCP 客户端服务器文件传输

转载 作者:太空狗 更新时间:2023-10-29 14:23:55 24 4
gpt4 key购买 nike

编辑*我在客户端服务器上成功了。现在我正在 2 个模拟器之间进行文件传输。该文件确实在模拟器之间传输,但我注意到收到的文件大小与原始文件不同。例如A.jpg大小为900KB,但接收到的文件小于900KB。我检查了文件传输大小,发现传输时丢失了一些数据(字节)。这是怎么回事?

代码如下:

客户端(发送文件)

File myFile = new File ("/mnt/sdcard/Pictures/A.jpg");
FileInputStream fis = new FileInputStream(myFile);
OutputStream os = socket.getOutputStream();
int filesize = (int) myFile.length();

byte [] buffer = new byte [filesize];
int bytesRead =0;
while ((bytesRead = fis.read(buffer)) > 0) {
os.write(buffer, 0, bytesRead);
//Log display exact the file size
System.out.println("SO sendFile" + bytesRead);
}
os.flush();
os.close();
fis.close();
Log.d("Client", "Client sent message");
socket.close();

服务器(接收文件)

FileOutputStream fos = new FileOutputStream("/mnt/sdcard/Pictures/B.jpg");
@SuppressWarnings("resource")
BufferedOutputStream bos = new BufferedOutputStream(fos);
InputStream is = clientSocket.getInputStream();

byte[] aByte = new byte[1024];
int bytesRead;
while ((bytesRead = is.read(aByte)) != -1)
{
bos.write(aByte, 0, bytesRead);
//Log display few parts the file size is less than 1024. I total up, the lost size caused the file received is incomplete
System.out.println("SO sendFile" + bytesRead);
}
clientSocket.close();

*编辑2

当我在谷歌上冲浪时,我发现 .read(buffer) 不能保证读取文件的完整大小(字节)。因此,接收到的文件总是会丢失一些字节(如空格、空字符)。为了解决这个问题,先发送文件大小通知接收方,然后才开始传输文件。

最佳答案

NetworkOnMainThreadException 发生是因为您必须使用 AsyncTask

NullPointerException 发生是因为您试图将 PrintWriter 与套接字的结果一起使用。由于您对套接字一无所知,因此您会收到此错误。

关于Android Java TCP 客户端服务器文件传输,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14098648/

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