我有一臺PC服務器和一個android客戶端;我的android客戶端啓動到服務器的套接字連接。android:TCP連接性能
雖然我連接到服務器,我也接收數據從服務器到Android客戶端;
這裏是我的代碼:
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%。
任何想法來解決這個問題?