我想将40x40px Blob发送到我的Python服务器,然后在其中进行处理,并发送回一个ID,该ID代表图像类(其图像分类任务)。我使用AsyncTask,并且出现了一个问题-将Blob发送到服务器,但是负责接收答复的部分未在我的Android代码中到达。

我想知道在单个AsyncTask中发送和接收数据是否正确。我已经读到,花费少于10秒的任务对于此解决方案来说是很好的,因此从理论上讲,我的情况应该没有问题。

在这里,我附上我的代码,用于Client:

public class ServerConnectAsyncTask extends AsyncTask<Void, Void, Integer> {

    private AsyncTaskResultListener asyncTaskResultListener;
    private Socket socket;
    private Mat img;

    ServerConnectAsyncTask(Mat blob, Context c) throws IOException {
        img = blob;
        asyncTaskResultListener = (AsyncTaskResultListener) c;
    }

    @Override
    protected Integer doInBackground(Void... voids) {
        MatOfByte buf = new MatOfByte();
        Imgcodecs.imencode(".jpg", img, buf);
        byte[] imgBytes = buf.toArray();

        try {
            socket = new Socket("192.168.0.109",8888);
            DataOutputStream dout = new DataOutputStream(socket.getOutputStream());
            DataInputStream din = new DataInputStream(socket.getInputStream());

            dout.write(imgBytes);
            dout.flush();

            String str = din.readUTF();     // it seems that it doesn't reach this line

            dout.close();
            din.close();
            socket.close();

            return Integer.valueOf(str);
        } catch (IOException e) {
            e.printStackTrace();
            return 99;
        }
    }

    @Override
    protected void onPostExecute(Integer imgClass) {
        asyncTaskResultListener.giveImgClass(imgClass);
    }
}


对于python服务器:

HOST = "192.168.0.109"
PORT = 8888

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))

s.listen(10)

while True:
    conn, addr = s.accept()
    print("Got connection from", addr)

    msg = conn.recv(4096)

    buf = np.frombuffer(msg, dtype=np.uint8).reshape(-1, 1)
    img = cv2.imdecode(buf, 0)
    cv2.imwrite("output.jpg", img)            # here I save my blob correctly

    if msg:
        message_to_send = "0".encode("UTF-8")     # then I send my "predicted" image class
        conn.send(message_to_send)
    else:
        print("no message")


同样重要的是,我在AsyncTask.execute()方法中调用onCameraFrame()-一次(不是在每一帧中,只有当我的blob足够“稳定”时才会发生),这种情况很少发生。

最佳答案

显然,它卡在了readUTF()部分。现在可以正常工作:

DataInputStream din = new DataInputStream(socket.getInputStream());
int str = din.read();
char sign = (char) str;

dout.close();
din.close();
socket.close();
return Character.getNumericValue(sign);


现在,当我从python服务器发送“ 0”时,它返回0,因此对我来说工作正常。

07-24 09:50
查看更多