[英]How to FAST transfer files from server to Android phone with Java?
I'm building an Android app that requires some files sent to it from our server. 我正在构建一个Android应用,该应用需要从我们的服务器发送给它的一些文件。 I've implemented both the Server Socket in Java and the Android socket client and tested it, but the transfer is too slow.
我已经用Java和Android套接字客户端实现了服务器套接字,并对其进行了测试,但是传输速度太慢。
FILE SIZE: 5 MB
TRANSFER TIME: 15.3 seconds
So the server is set up on my own PC, I use port forwarding so I can be able to connect to it from any network. 因此,服务器是在我自己的PC上设置的,所以我使用端口转发,因此可以从任何网络连接到它。 If you think it's relevant, here is a speed test of my network: http://www.speedtest.net/my-result/3965566858
如果您认为这是相关的,这是我的网络的速度测试: http : //www.speedtest.net/my-result/3965566858
Now the server code: 现在服务器代码:
BufferedInputStream musicData = new BufferedInputStream(new FileInputStream(new File("fileSrc")));
byte[] data = new byte[8192];
int count = 0;
while ((count = musicData.read(data)) > 0) {
outStreamMusic.write(data, 0, count);
}
Client code: 客户代码:
InputStream inStream = socketClient.getInputStream();
byte[] data = new byte[8192];
int count = 0;
while ((count = inStream.read(data)) > 0) {
tempFile.write(data, 0, count);
}
So this will open the file, parse it and send bytes until there's nothing else to send. 因此,这将打开文件,解析文件并发送字节,直到没有其他可发送的内容为止。 I'm pretty sure this can be done faster but I have no idea how.
我很确定这可以更快地完成,但我不知道如何做。 The Android client just opens a socket to my ip/port and reads data from it.
Android客户端只是打开我的ip / port的套接字并从中读取数据。 Any idea how to make this faster?
任何想法如何使它更快?
IF you want your android device to read data from a server, its best done using the android AsynTask and implement the doInBackground method. 如果您希望Android设备从服务器读取数据,则最好使用android AsynTask并实现doInBackground方法。 This way you can establish a connection to your server using HttpClient of the org.apache library and issue a request and receive a response in which your can read it through from an inputStream.
这样,您可以使用org.apache库的HttpClient建立与服务器的连接,并发出请求并接收响应,您可以在其中从inputStream中读取该响应。
public String doInBackground()
{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("www.yourserverip.com");
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
BufferReader reader = new BufferReader(new InputStreamReader(entity.getContent()));'
while(reader.readLine!=null)
{
//Read Something
//read Your data
}
/*Note this is just a basic use of httpClient*/
/*Also if its a file you really might not use the bufferedReader*/
}
First Of all I really hope i understand your question and what you really want to achieve. 首先,我真的希望我能理解您的问题以及您真正想要实现的目标。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.