Reputation: 11
I'm new to Java and Android programming but there's this project that required me to do so.
The app sends bytes to a server that receives all information send to it and performs the equivalent commands. The client and server is in an exclusive link so I would not worry about security issues.
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;
}
}
With the code above I was able to establish connection to the server but the data is only sent/written to the socket every 1-2 seconds.
Is there a way to perform this continuously? or with minimal delay (around 0.5 seconds or less?)
Battery life is not an issue for me and I accept that a socket active continuously has its cons.
Thanks.
Upvotes: 1
Views: 1543
Reputation: 3489
Try do it this way:
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;
}
}
Upvotes: 3