我在将文件从服务器(桌面应用程序)发送到客户端(Android)时遇到一些问题......
在发送文件之前,服务器会发送元数据,如文件大小、名称等......
服务器端发送方法:
private void sendPdfData(OutputStream os, File file) throws IOException {
os.flush();
FileInputStream fis = new FileInputStream(file);
byte[] buffor = new byte[1024];
long count = 0L;
long size = file.length();
int current = 0;
while (count < size) {
current = fis.read(buffor, 0, buffor.length);
os.write(buffor, 0, current);
count += current;
}
fis.close();
os.flush();
}
客户端接收方法:
@Override
protected String doInBackground(Void... params) {
String pathToPdf = "";
if (pdf.getLength() > 0) {
InputStream is;
try {
byte b = 0;
clientSocket.getOutputStream().write(b);
is = clientSocket.getInputStream();
pathToPdf = pathToExternalStorageFolder+pdf.getMeta().getName();
pathToPdf = pathToPdf.replace(".\\", "/");
pathToPdf = pathToPdf.replace("\\", "/");
int size = pdf.getLength();
byte[] buffor = new byte[1024];
int current = 0;
int count = 0;
if (pdf.getMeta() != null) {
FileOutputStream fos = new FileOutputStream(pathToPdf);
while (count < size) {
current = is.read(buffor, 0, buffor.length);
fos.write(buffor, 0, current);
count += current;
}
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return pathToPdf;
}
发送文件时的一些随机错误:
java.net.SocketException: Software caused connection abort: socket write error
java.net.SocketException: Connection reset by peer: socket write error
File size: 2317679
Sended: 44032
更新 08.09.2013
我创建桌面客户端应用程序来检查服务器应用程序。当我在 NetBeans 中运行服务器和客户端时,一切都运行良好,我使用接口地址(不是 lopback)。当我从 jar 运行客户端时出现问题:文件列表为空,但在服务器端不为空且不为空,当从 android 连接时,我得到文件列表 wtfigo - 魔术。