我是 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 秒或更短?)
电池生命周期对我来说不是问题,我接受持续激活的 socket 有其缺点。
谢谢。
最佳答案
- 您在“while” block 中创建了多个套接字
- 在第二个链接上,您也在“while” block 中创建了多个输出流
尝试这样做:
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;
}
}
关于java - Android:连续套接字写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9155070/