【发布时间】:2020-08-24 03:49:22
【问题描述】:
我只是想从一个套接字发送一些文件,并且我能够在没有任何中断的情况下发送这些文件:无论大小文件是小还是大,它都没有关系,它就像一个魅力一样发送。
但在我的情况下出现的问题是我发送的文件已损坏,即它不像音频或视频那样播放。我已经通过this,但它没有帮助。
我使用的代码如下。
服务器端:
File file = new File(
Environment.getExternalStorageDirectory(),
"testingFile.mp4");
byte[] mybytearray = new byte[4096];
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);
OutputStream os;
DataOutputStream dos = null;
try {
os = socket.getOutputStream();
dos = new DataOutputStream(os);
dos.writeUTF(file.getName());
dos.writeLong(mybytearray.length);
int read;
while ((read = dis.read(mybytearray)) != -1) {
dos.write(mybytearray, 0, read);
}
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (dos != null) {
dos.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
还有客户端:
File file = new File(
Environment.getExternalStorageDirectory(),
"TEST SUCCESS.mp4");
InputStream in = null;
int bufferSize;
try {
bufferSize = socket.getReceiveBufferSize();
in = socket.getInputStream();
DataInputStream clientData = new DataInputStream(in);
String fileName = clientData.readUTF();
System.out.println(fileName);
OutputStream output = new FileOutputStream(
file);
byte[] buffer = new byte[bufferSize];
int read;
while ((read = clientData.read(buffer)) != -1) {
output.write(buffer, 0, read);
}
output.flush();
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (in != null) {
in.close();
}
}
提前致谢。
【问题讨论】:
-
您能否向我们展示一个显示损坏的小文件的结果?请向我们展示原始文件,然后是损坏的文件。对不起;我假设这些是文本文件,而不是 mp4。
-
@NomadMaker 我正在发送 mp4 文件而不是文本。请帮我解决这个问题
-
您正在从一个
Socket发送到另一个。ServerSocket与此无关。 -
由于某种原因,您使用
dos.writeLong(mybytearray.length)发送缓冲区大小,但您从未读取它,因此它会在所有数据之前进入文件。你不需要这个。删除并重新测试。 -
@MarquisofLorne 所以请给我一些代码建议,以便我可以解决这个问题
标签: java sockets file-sharing