私はPCサーバーとアンドロイドクライアントを持っています。私のアンドロイドクライアントはサーバとのソケット接続を開始します。アンドロイド:TCP接続のパフォーマンス
私はサーバーに接続している間、サーバーからアンドロイドクライアントにもデータを受け取ります。
は、ここに私のコードです:
Socket socket = null;
DataOutputStream out = null;
DataInputStream in = null;
InputStream inputStream = null;
OutputStream outputStream = null;
...
public void connectToTCP()
{
try
{
socket = new Socket(HOST_ADDRESS, PORT);
socket.setSoTimeout(30000);
outputStream = socket.getOutputStream();
out = new DataOutputStream(outputStream);
inputStream = socket.getInputStream();
in = new DataInputStream(inputStream);
Log.e("TCP-", "Connected");
while (socket.isConnected()){readBytes();}
}
catch (UnknownHostException e)
{
Log.e("Error in tcp connection","Unknown Host");
}
catch (IOException e)
{
Log.e("Error in tcp connection", "Couldn't get I/O for the connection");
}
}
public void readBytes() throws IOException
{
if (in.available() > 0)
{
byte[] buffer = new byte[in.available()];
if (buffer.length > 0)
{
if (mListener != null)
{
int numberOfBytes = in.read(buffer);
mListener.tcpConnectionDataReceived(buffer, numberOfBytes);
}
}
}
}
が、私の問題はパフォーマンスです。私は、デバイス上のコードをテストし、(タスクマネージャから)アプリケーションが多くのリソース(CPU使用率が50%以上)を消費することに気づいたが、ループを削除してソケットからの読み取りを停止すると、while (socket.isConnected()){readBytes();}
CPU使用率が1%。
これを解決する方法はありますか?