[英]Java Async Task / Socket connection problem
我在 Java 中遇到异步任务问题:
我有一个移动应用程序将图像发送到我的服务器,然后从该服务器接收另一个图像,然后通过套接字/端口接收 0 到 100 之间的 7 个 int 值。 所以我有一个 AsnycTask,我在 DoInBackground 方法中完成所有连接/发送/接收的工作。 图像工作正常,但问题是 int[]:我有一个长度为 7 的概率 [] int-array 我将接收到的值(在 DoInBackground 中)。 然后,在 onPostExecute 我调用我自己的 function ,我需要这些值。
现在的问题是:有时这些值在那里,有时数组仍然只有 0(我确信数据不仅是零)。
这是我的 AsnyTask 代码
class ConnectTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... voids) {
try {
//Connect to my PC and send my image from my phone
Socket photoSocket = new Socket(IP_ADDRESS, PORT_NO);
DataOutputStream dos = new DataOutputStream(photoSocket.getOutputStream());
FileInputStream fis = new FileInputStream(pathname);
int size = fis.available();
byte[] data = new byte[size];
fis.read(data);
dos.write(data);
dos.flush();
fis.close();
dos.close();
photoSocket.close();
//now receive the other image from server
ServerSocket serverSocket = new ServerSocket(1235);
Socket incomingSocket = serverSocket.accept();
InputStream is = incomingSocket.getInputStream();
FileOutputStream fos = new FileOutputStream(Environment.getExternalStorageDirectory() + "/image_from_server.jpg");
BufferedOutputStream bos = new BufferedOutputStream(fos);
byte[] aByte = new byte[40000];
int bytesRead;
while ((bytesRead = is.read(aByte)) != -1) {
bos.write(aByte, 0, bytesRead);
}
is.close();
fos.close();
bos.close();
serverSocket.close();
incomingSocket.close();
//now Receive Values (ints)
ServerSocket serverSocket2 = new ServerSocket(1236);
Socket incomingSocket2 = serverSocket2.accept();
InputStream inputstream = incomingSocket2.getInputStream();
byte[] data2 = new byte[7];
inputstream.read(data2);
//Fill array with received ints THIS IS SOMETIMES WORKING, SOMETIMES probabilities[] STAYS FILLED WITH 0s
for (int i = 0; i < data2.length; i++){
probabilities[i] = data2[i];
}
serverSocket2.close();
incomingSocket2.close();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPreExecute() {
//irrelevant
}
@Override
protected void onPostExecute(Void aVoid) {
File xaifile = new File(Environment.getExternalStorageDirectory() + "/image_from_server.jpg");
//...doing some UI stuff
//..................
//..................
//now call function where i replace picture. Since this is in the "postExecute" method, my probabilities[] should have been filled with data since its in the doInBackground method.
replacePicture(xaifile);
}
}
ConnectTask connect = new ConnectTask();
Void[] param = null;
//execute Async task
connect.execute(param);
inputstream.read(data2) 可能返回 -1,这意味着没有读取任何字节,并且 data2 保持为零,因此如果 read 返回 -1,则处理并重试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.