我是Java和Android编程的新手,但是这个项目要求我这样做。
应用程序将字节发送到服务器,该服务器接收发送给它的所有信息并执行等效命令。客户端和服务器处于独占链接中,因此我不担心安全问题。
public class NetworkTask extends AsyncTask<Void, byte[], Boolean> {
OutputStream dataOut; //Network Output Stream
@Override
protected void onPreExecute() {
Log.i("AsyncTask", "onPreExecute");
}
@Override
protected Boolean doInBackground(Void... params) {
boolean result = false;
while (sendData) { //While Boolean sendData is true
try {
gsocket = new Socket(roubotIP, roubotPort);
byte[] data = EncodingUtils.getAsciiBytes(outData);
Log.i("Data: ", outData);
dataOut = new DataOutputStream(gsocket.getOutputStream());
dataOut.write(data);
} catch (UnknownHostException e) {
Log.i("Socket: ","Unkown host");
e.printStackTrace();
result = true;
} catch (IOException e) {
e.printStackTrace();
result = true;
} catch (Exception e) {
e.printStackTrace();
result = true;
}
}
try {
dataOut.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
使用上面的代码,我能够建立与服务器的连接,但数据仅每1-2秒发送/写入套接字。
有没有办法连续执行此操作?或者延迟最小(约0.5秒或更短?)
电池续航时间对我来说不是问题,我接受持续有效的插座有其缺点。
感谢。
答案 0 :(得分:3)
尝试这样做:
public class NetworkTask extends AsyncTask<Void, byte[], Boolean> {
OutputStream dataOut; //Network Output Stream
@Override
protected void onPreExecute() {
Log.i("AsyncTask", "onPreExecute");
}
@Override
protected Boolean doInBackground(Void... params) {
try {
gsocket = new Socket(roubotIP, roubotPort);
dataOut = new DataOutputStream(gsocket.getOutputStream());
} catch (UnknownHostException e) {
Log.i("Socket: ","Unkown host");
e.printStackTrace();
return false;
} catch (Exception e) {
e.printStackTrace();
return false;
}
while (sendData) { //While Boolean sendData is true
try {
byte[] data = EncodingUtils.getAsciiBytes(outData);
Log.i("Data: ", outData);
dataOut.write(data);
dataOut.flush();
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
try {
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
}