最近我的任务是在 Nexus 7 平板电脑上开发 Android 应用程序,该应用程序将使用 wifi 通过 tcp 套接字与 pc 连接。
特别是我必须将图像流(例如未压缩的 BMP)传递给平板电脑。所以我做了简单的测试来检查带宽并且对结果感到失望。我将平板电脑放在 wifi 信号源前面,上面写着连接速度是每秒 54Mb,但考虑到测试结果,我每秒只能得到 ~16Mb。
测试代码:
个人电脑:
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);
}
}
安卓:
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();
}
}
我错过了什么?