我正在创建一个应用程序,以使用 http 套接字程序将文件从 android 设备发送到另一台设备。这是代码,服务器端
try {
ServerSocket servsock = new ServerSocket(4042);
File myFile = new File(pathToFile);
while (true) {
Socket sock = servsock.accept();
byte[] mybytearray = new byte[(int) myFile.length()];
BufferedInputStream bis = new BufferedInputStream(
new FileInputStream(myFile));
bis.read(mybytearray, 0, mybytearray.length);
OutputStream os = sock.getOutputStream();
os.write(mybytearray, 0, mybytearray.length);
os.flush();
bis.close();
sock.close();
}
} catch (Exception e) {
Toast.makeText(MyActivity.context,
"Failed to send file!", Toast.LENGTH_SHORT)
.show();
}
而客户端,
try {
Socket sock = new Socket(ipAddress, 4042);
byte[] mybytearray = new byte[1024];
InputStream is = sock.getInputStream();
FileOutputStream fos = new FileOutputStream("/mnt/sdcard/"
+fileName);
BufferedOutputStream bos = new BufferedOutputStream(fos);
int bytesRead = is.read(mybytearray, 0, mybytearray.length);
bos.write(mybytearray, 0, bytesRead);
bos.close();
sock.close();
} catch (Exception e) {
Toast.makeText(MyActivity.context,
"Failed to download the file!", Toast.LENGTH_LONG)
.show();
}
这两个代码都在 AsyncTask 类中。但是客户端总是超时。这是在 android 中通过 Internet 传输文件的正确方法吗?如果是这样,请告诉我我做错了什么。提前致谢。
编辑:在这里,文件需要在服务器端发送,客户端正在尝试下载该文件。