[英]Is it possible in android to transfer file over http using java socket program?
I'm creating an application to send a file from an android device to another device using http socket program. 我正在创建一个应用程序,以使用http套接字程序将文件从android设备发送到另一设备。 Here's the code, Server Side 这是服务器端的代码
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();
}
And the client side, 还有客户端
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();
}
Both these codes are in an AsyncTask class. 这两个代码都在AsyncTask类中。 But client side is always getting timed out. 但是客户端总是总是超时。 Is this the right way to transfer a file over Internet in android? 这是在Android中通过Internet传输文件的正确方法吗? If so, please tell me where I'm doing wrong. 如果是这样,请告诉我我在哪里做错了。 Thanks in advance. 提前致谢。
EDIT : Here, the file needs to be send in Server side and Client is trying to download that file. 编辑:在这里,该文件需要在服务器端发送,并且客户端正在尝试下载该文件。
In the server side code: 在服务器端代码中:
byte[] mybytearray = new byte[(int) myFile.length()];
If myFile is the destination, and you have just created it (meaning the file does not yet exist), then myFile.length() would be 0. That means you are creating a buffer of size 0, reading 0 bytes. 如果myFile是目的地,而您刚刚创建了它(意味着文件尚不存在),则myFile.length()将为0。这意味着您正在创建大小为0的缓冲区,读取0字节。
Server needs to know how much data to read from the socket. 服务器需要知道要从套接字读取多少数据。 A workaround could be that the android app first writes the length of the file, server reads it and creates a buffer according to that, and after that you write the complete file. 一种解决方法是,Android应用程序首先写入文件的长度,服务器读取该文件的长度并根据该长度创建一个缓冲区,然后再写入完整的文件。 Also, I suggest you move your .close()
calls to a finally block. 另外,我建议您将.close()
调用移至finally块。
Or, you could just use for example Apache FTP Client on Android and your favorite FTP server on the server side. 或者,您可以只使用例如Android上的Apache FTP客户端 ,以及服务器端上喜欢的FTP服务器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.