我有一台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%。
任何想法来解决这个问题?