I’m trying to send .yuv image file through tcp socket but some amount of byte array transfered and image build but not get 100% image it shows only 10% of image. I used Async Task for receive continuously image data in server side.
Here Server Side Code
public class TcpServer extends AppCompatActivity {
Button btSendData;
TextView tvDisplayData, tvIp;
EditText edtInput;
BufferedWriter outWriter = null;
private ServerSocket serverSocket;
boolean isActivityRun = true;
private int port = 5555;
byte() message;
ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tcp_server);
btSendData = findViewById(R.id.bt_send);
tvDisplayData = findViewById(R.id.tv_display_data);
tvIp = findViewById(R.id.tv_ip);
edtInput = findViewById(R.id.edt_input);
imageView = findViewById(R.id.imgae);
//Get local Ip address
WifiManager wm = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
// Toast.makeText(this, wm.getConnectionInfo().getIpAddress()+"", Toast.LENGTH_SHORT).show();
String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
tvIp.setText(ip);
//Strict mode policy used for performing network related operation in main thread.
//Network access on the application's main thread
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
btSendData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (outWriter != null) {
try {
String data = edtInput.getText().toString() + "rn";
outWriter.write(data);
outWriter.flush();
} catch (Exception e) {
Toast.makeText(TcpServer.this, "Client is not connected", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
} else {
Toast.makeText(TcpServer.this, "Client is not connected", Toast.LENGTH_SHORT).show();
}
}
});
new Thread() {
@Override
public void run() {
try {
serverSocket = new ServerSocket(port);
while (isActivityRun) {
Socket socket = serverSocket.accept();
Log.d("server", socket.getInetAddress() + "");
socket.setKeepAlive(true);
new IncomingClient().execute(socket);
}
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
try {
if (serverSocket != null) {
serverSocket.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
e.printStackTrace();
}
}
}.start();
}
private class IncomingClient extends AsyncTask<Socket, byte(), String> {
String response = "";
Socket socket;
BufferedWriter out;
byte() buf;
String data = "";
@Override
protected void onPreExecute() {
super.onPreExecute();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Client Connected", Toast.LENGTH_SHORT).show();
}
});
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
protected String doInBackground(Socket... sockets) {
try {
socket = sockets(0);
// Creating new socket connection to the IP (first parameter) and its opened port (second parameter)
out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
outWriter = out;
InputStream inputStream = socket.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// String outMsg = "Client accepted";
// Write message to stream
//out.write(outMsg);
// out.flush();
// Flush the data from the stream to indicate end of message
// out.flush();
String line;
byte() buffer = new byte(30000);
int bytes;
int tot=0;
byte() b1=null;
// List<Byte> list = new List<Byte>();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while ((bytes=inputStream.read(buffer)) != -1) {
Log.d("TAGGGG", "bytes " + bytes);
bos.write(buffer, 0, bytes);
tot = tot+bytes;
// data = data + new String(buffer, StandardCharsets.UTF_8).trim();
Log.d("TAGGGG", "length " + tot);
/* if (data.contains("<get_device_info:")){
sendData("<,device_info,02:00:00:00:00:00,863077040053161,>");
}else if (data.contains("<get_device_status:")){
sendData("<,device_status,0,51.73504638671875@59.46295166015625,>");
}
*/
if(tot>40000) {
Log.d("TAG Server","buf "+buffer.length);
publishProgress(buffer);
tot = 0;
Log.d("TAG Server","tot "+tot);
bos.flush();
}
}
/* while ((line = in.readLine()) != null) {
String data = line.trim();
Log.d("TAG", "Data:- " + data);
byte() encoded = Base64.decode(data, Base64.DEFAULT);
if (data.contains("<get_device_info:")){
sendData("<,device_info,02:00:00:00:00:00,863077040053161,>");
}else if (data.contains("<get_device_status:")){
sendData("<,device_status,0,51.73504638671875@59.46295166015625,>");
}
publishProgress(encoded);
}*/
socket.close();
} catch (Exception ex) {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response;
}
private void sendData(String s) {
try {
out.write(s + "nr");
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void onPostExecute(String response1) {
super.onPostExecute(response1);
Toast.makeText(getApplicationContext(), "Client Disconnected", Toast.LENGTH_SHORT).show();
}
@Override
protected void onProgressUpdate(byte()... values) {
//Update the progress of current task
super.onProgressUpdate(values);
Log.d("values","____________"+values(0));
// Log.v("response", "" + values(0));
// tvDisplayData.setText(values(0)
/* File file = new File(Environment.getExternalStorageDirectory(),"/Image.yuv");
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write(values(0));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}*/
try {
byte() b1 = values(0);
/* if(buf !=null) {
byte() c = new byte(buf.length + b1.length);
System.arraycopy(buf, 0, c, 0, buf.length);
System.arraycopy(b1, 0, c, buf.length, b1.length);
buf = new byte(c.length);
buf=c;
}else{
buf=b1;
}*/
// if(buf.length==614400) {
Log.d("Data", "Data length" + b1.length);
ByteArrayOutputStream out = new ByteArrayOutputStream();
YuvImage yuvImage = new YuvImage(values(0), ImageFormat.YUY2, 640, 480, null);
yuvImage.compressToJpeg(new Rect(0, 0, yuvImage.getWidth(), yuvImage.getHeight()), 100, out);
byte() imageBytes = out.toByteArray();
Bitmap image = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
imageView.setImageBitmap(image);
// }
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Override
protected void onDestroy() {
isActivityRun = false;
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
super.onDestroy();
}
}
Client Code
public class TcpClient extends AppCompatActivity {
Button btSendData;
Button btConnect;
TextView tvDisplayData;
EditText edtInput, edtIp;
BufferedWriter outWriter = null;
Socket socket;
boolean isConnect = false;
AsyncTask<String, String, String> asyncClient;
String s;
OutputStream socketOutputStream;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tcp_client);
btSendData = findViewById(R.id.bt_send);
btConnect = findViewById(R.id.bt_connect);
tvDisplayData = findViewById(R.id.tv_display_data);
edtInput = findViewById(R.id.edt_input);
edtIp = findViewById(R.id.edt_ip);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
btSendData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (outWriter != null) {
File file = new File(Environment.getExternalStorageDirectory(), "/" + "sample_image.yuv");
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
byte() b1 = null;
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
b1 = new byte(fis.available());
for (int readNum; (readNum = fis.read(b1)) != -1; ) {
bos.write(b1, 0, readNum);
}
// byte() encoded = Base64.encode(b1, Base64.DEFAULT);
socketOutputStream.write(b1);
Log.d("TAG", "Length of b1:- " + b1.length);
Log.d("TAG", "client " + b1);
socketOutputStream.flush();
/* byte() b2={0x0D,0x0A};
socketOutputStream.write(b2);
socketOutputStream.flush();*/
} catch (Exception e) {
e.printStackTrace();
}
/* String str = new String(b1);
Log.d("TAG", "___________-------------------___________________");
Log.d("TAG", "value" + str);
Log.d("TAG", "value" + str.length);
Log.d("TAG", "__________--------------------____________________");
*/
try {
/*outWriter.write(b1);
outWriter.flush();*/
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), "Please Connect", Toast.LENGTH_SHORT).show();
}
}
});
btConnect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("res", "isCon " + isConnect);
if (!isConnect) {
asyncClient = new AsyncClient().execute(edtIp.getText().toString().trim());
//asyncClient.cancel(true);
} else {
// btConnect.setText("Connect");
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Toast.makeText(TcpClient.this, "Disconnect", Toast.LENGTH_SHORT).show();
}
}
});
}
/* private byte() readfile(File file) {
FileInputStream fileInputStream = null;
byte() bFile = new byte((int) file.length());
try {
//convert file into array of bytes
fileInputStream = new FileInputStream(file);
fileInputStream.read(bFile);
fileInputStream.close();
for (int i = 0; i < bFile.length; i++) {
System.out.print((char) bFile(i));
}
} catch (Exception e) {
e.printStackTrace();
}
return bFile;
}*/
private byte() getByte(String path) {
byte() getBytes = {};
try {
File file = new File(path);
getBytes = new byte((int) file.length());
InputStream is = new FileInputStream(file);
is.read(getBytes);
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return getBytes;
}
private class AsyncClient extends AsyncTask<String, String, String> {
String response = "";
@Override
protected void onPreExecute() {
super.onPreExecute();
runOnUiThread(new Runnable() {
public void run() {
isConnect = true;
btConnect.setText("Disconnect");
Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_SHORT).show();
}
});
}
@Override
protected String doInBackground(String... ip) {
try {
// Creating new socket connection to the IP (first parameter) and its opened port (second parameter)
socket = new Socket();// new Socket(Constant.SERVER_IP_TEMP, 8888);//portquiz.net52.47.209.216
socket.connect(new InetSocketAddress(ip(0).trim(), 5555), 10000);
// socket.setSoTimeout(10000);
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
outWriter = out;
socketOutputStream = socket.getOutputStream();
//
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
isConnect = true;
while ((line = in.readLine()) != null && isConnect) {
String data = line;
publishProgress(data);
}
isConnect = false;
socket.close();
} catch (Exception ex) {
isConnect = false;
ex.printStackTrace();
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response;
}
@Override
protected void onPostExecute(String response1) {
super.onPostExecute(response1);
btConnect.setText("Connect");
isConnect = false;
}
@Override
protected void onCancelled() {
super.onCancelled();
isConnect = false;
if (socket != null) {
try {
socket.close();
outWriter = null;
} catch (IOException e) {
e.printStackTrace();
}
}
Log.v("response", "on Cancel");
}
@Override
protected void onProgressUpdate(String... values) {
//Update the progress of current task
super.onProgressUpdate(values);
Log.v("response", values(0));
tvDisplayData.setText(values(0));
}
}
}
(I got this output when I send image first time1