问题
Recently I was given a task to develop Android app on Nexus 7 tablet, which would be conneted with pc via tcp sockets using wifi.
Particularly I had to pass stream of images (uncompressed BMP for example) to tablet. So I made simple test to check bandwidth and was dissapointed by results. I'm siting with my tablet just in front of wifi signal sourse, it's written that connection speed is 54Mb per sec, but I get only ~16Mb per sec considering test results.
Test code:
PC:
public static void main(String[] args) throws Exception
{
Socket socket = new Socket(androidIpAddr, port);
OutputStream output = socket.getOutputStream();
byte[] bytes = new byte[1024 * 100]; // 10K
for (int i = 0; i < bytes.length; i++) {
bytes[i] = 12;
} // fill the bytes
// send them again and again
while (true) {
output.write(bytes);
}
}
Android:
public class MyActivity extends Activity {
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new Thread(new Runnable()
{
public void run()
{
ServerSocket server = new ServerSocket(port);
Socket socket = server.accept();
InputStream input = socket.getInputStream();
long total = 0;
long start = System.currentTimeMillis();
byte[] bytes = new byte[1024 * 100]; // 10K
// read the data again and again
while (true)
{
int read = input.read(bytes);
total += read;
long cost = System.currentTimeMillis() - start;
if (cost > 100)
{
double megaBytes = (total / (1024.0 * 1024));
double seconds = (cost / 1000.0);
System.out.println("Read " + total + " bytes, speed: " + megaBytes / seconds + " MB/s");
start = System.currentTimeMillis();
total = 0;
}
}
}
}).start();
}
}
What did I missed?
回答1:
Ok, first Wifi that is 54Mbps is 54 x 1024 x 1024 bits per second. So maximum 6.75 MB/s.
I did the experiment on my network that reports as 54 Mbps in my windows 7 box. Between my Windows 7 box (server) and XP box (client) I achieved 3.0 MB/s using basically the code above.
I then ran the same code between my Nexus 7 (server) and XP (client) and got 0.3 MB/s. So a significant drop-off in speed. I put the following in the constructor of the server thread:
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
and in the MANIFEST:
<uses-permission android:name="android.permission.RAISED_THREAD_PRIORITY"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
I also moved near the router and turned wifi off and then back on. It reported on the Nexus 7 as 54Mbps and when I ran it I got 3.0 MB/s.
So at this point same outcome as Windows 7 and about 44% of theoretical network throughput.
Using more than one TCP connection may allow us to get closer to 100% throughput.
来源:https://stackoverflow.com/questions/15049030/android-wifi-bandwidth