I have an android app that opens a socket connection and sends an image to a python server. The image is continously received for as long as the user presses the capture button. However, what I want to do is return a string/text confirming the image has arrived to the user client.
This is my Python server that receives the image as bytes decodes and saves it to a directory then sends a message back:
from socket import *
import datetime
import cv2
import PIL.Image as Image
from PIL import ImageFile, Image
import io
import base64
import numpy as np
import pickle
import uuid
date_string = datetime.datetime.now().strftime("%Y-%m-%d-%H:%M")
port = 9999
s = socket(AF_INET, SOCK_STREAM)
s.bind(('', port))
s.listen(1)
while True:
conn, addr = s.accept()
img_dir = '/home/Desktop/frames_saved/'
img_format = '.png'
try:
print("Connected by the ",addr)
#date_string = datetime.datetime.now().strftime("%Y-%m-%d-%H:%M")
filename = str(uuid.uuid4())
with open(img_dir+filename+img_format, 'wb') as file:
while True:
data = conn.recv(1024*8)
if data:
print(data)
try:
file.write(data)
except:
s = socket(AF_INET, SOCK_STREAM)
s.bind(('', port))
s.listen(1)
conn.sendall(("Hello World"))
else:
print("no data")
break
finally:
conn.close()
What I am trying to do is receive the encoded string in my android client and print/show a toast.
Android client code:
public class SendImageClient extends AsyncTask<byte[], Void, Void> {
@Override
protected Void doInBackground(byte[]... voids) {
isSocketOpen = true;
try {
Socket socket = new Socket("192.168.0.14",9999);
OutputStream out=socket.getOutputStream();
DataOutputStream dataOutputStream = new DataOutputStream(out);
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while (isSocketOpen){
Log.d("IMAGETRACK", "Wrote to the socket[1]");
dataOutputStream.write(voids[0],0,voids[0].length);
out.close();
Log.d("IMAGETRACK2", "Wrote to the socket[2]");
while ((line = input.readLine()) != null)
Log.d("IMAGETRACK3", "Wrote to the socket[3]");
response.append(line);
Message clientmessage = Message.obtain();
clientmessage.obj = response.toString();
Log.d("[MESSAGE]", String.valueOf(clientmessage));
if(isSocketOpen == false){
socket.close();
input.close();
Log.d("CLOSED", "CLOSED CONNECTION");
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
I am not experienced with streams in Java. The problem with my code is that the string is apparently sent, but is not received by the android client even though i can always send a new image as the server is still running. How can I receive a string from a python server after the image is sent?
from Android - Receiving string from server after sending an image
No comments:
Post a Comment