简体   繁体   中英

Android: trouble to send bitmap byte array over socket

With relation to my last question , i now have trouble to send Bitmap byte array for server side.

Small explanation about this project example (the same of my previous question):

Server sends a string command requesting a screenshot to Client .apk, then if this specific string is received by Client, so Client executes a method called in my code below of getBytes() where this method is responsible for: Capture screenshot of device as Bitmap, Transform this Bitmap in a bytes array, Compress this bytes array using ZLIB library and finally sends this bytes array compressed to server side..

Apparently all seems ok, but nothing is received in server side.

package com.example.client;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.zip.Deflater;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import android.app.Activity;
import android.graphics.Bitmap;

public class MainActivity extends Activity {

    Socket clientSocket;

    private static final int SERVERPORT = 60;
    private static final String SERVER_IP = "192.168.25.227";

    byte[] tmpbytes = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        new Thread(new ClientThread()).start();

    }

        public Bitmap takeScreenshot() {

           View rootView = findViewById(android.R.id.content).getRootView();
           rootView.setDrawingCacheEnabled(true);
           return rootView.getDrawingCache();

        }

        ///////////////////////  ZLIB compression library. ////////////////////////////////

        public static byte[] compress(byte[] data) throws IOException {  

               Deflater deflater = new Deflater();  
               deflater.setInput(data);  
               ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);   
               deflater.finish();  
               byte[] buffer = new byte[1024];   
               while (!deflater.finished()) {  
                int count = deflater.deflate(buffer);   
                outputStream.write(buffer, 0, count);   
               }  
               outputStream.close();  
               byte[] output = outputStream.toByteArray();  

               return output;

              }  

        /////////////////////////////////////////////////////////////////////////////////

        public void getBytes() throws IOException {

            try
            {

            Bitmap bitmap = takeScreenshot();


            int bytes = bitmap.getByteCount();
            ByteBuffer buffer = ByteBuffer.allocate(bytes); 
            bitmap.copyPixelsToBuffer(buffer); 

            byte[] array = buffer.array();
            byte[] arrsmall = compress(array); // Compress

            boolean retval = Arrays.equals(arrsmall, tmpbytes);

            if (!retval)
            {

                OutputStream out = clientSocket.getOutputStream(); 
                DataOutputStream dos = new DataOutputStream(out);
                dos.writeInt(arrsmall.length);
                dos.write(arrsmall, 0, arrsmall.length);
                dos.flush();

                tmpbytes = arrsmall;

            }

          }

            catch (UnknownHostException e) {
                //System.out.println(e.toString());
            } 

            catch (IOException e) {
                //System.out.println(e.toString());
            } 

            catch (Exception e1) {
                //Log.e("clients", e1.toString());
                //Toast.makeText(MainActivity.this, e1.toString(), Toast.LENGTH_LONG).show();
                System.out.println(e1.toString());
            }

        }

        class ClientThread implements Runnable { 

            @Override
            public void run() {

                try {

                    InetAddress serverAddr = InetAddress.getByName(SERVER_IP);

                    clientSocket = new Socket(serverAddr, SERVERPORT);

                    new Thread(new CommsThread()).start();

                } catch (Exception e1) {
                    //Log.e("clients", e1.toString());
                    //Toast.makeText(MainActivity.this, e1.toString(), Toast.LENGTH_LONG).show();
                    System.out.println(e1.toString());
                } 

            }
        }


        class CommsThread implements Runnable {

            @Override
            public void run() {

                try {

                while(clientSocket.isConnected() && !Thread.currentThread().isInterrupted()){

                    //System.out.println("Waiting for server request");

                    BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

                    String message = reader.readLine();

                    if(message != null && !message.trim().isEmpty()) {

                    System.out.println("Message Received: " + message);

                    if(message.equalsIgnoreCase("screen"))

                        getBytes();

                    }

                    reader.close();

                    //clientSocket.close();

                    if(message.equalsIgnoreCase("exit")) break;

                    Thread.sleep(100);
                }
                System.out.println("Shutting down Socket!!");
                clientSocket.close();
                } catch (Exception e1) {
                    //Log.e("clients", e1.toString());
                    //Toast.makeText(MainActivity.this, e1.toString(), Toast.LENGTH_LONG).show();
                    System.out.println(e1.toString());
                } 

            }

            }

}

LogCat below

When apk is started:

E        08-19 15:41:40.071: E/MoreInfoHPW_ViewGroup(6421): Parent view is not a TextView

E        08-19 15:41:40.341: E/ION(6421): ION_IOC_CUSTOM_GET_CONFIG ioctl Failed. Use default

Only when i close server, LogCat show that string command was rceived:

I        08-19 15:42:20.350: I/System.out(6421): Message Received: screen

I        08-19 15:42:20.380: I/dalvikvm-heap(6421): Grow heap (frag case) to 10.888MB for 1536016-byte allocation

E        08-19 15:42:20.420: E/dalvikvm(6421): adjustAdaptiveCoef max=4194304, min=1048576, ut=568

E        08-19 15:42:20.440: E/dalvikvm(6421): adjustAdaptiveCoef max=6291456, min=1572864, ut=368

E        08-19 15:42:20.470: E/dalvikvm(6421): adjustAdaptiveCoef max=8388608, min=2097152, ut=256

I        08-19 15:42:20.630: I/System.out(6421): java.net.SocketException: Socket is closed

Any suggestion here, will welcome. :-)

Just a suggestion, instead of using custom sockets and threads you could just try many of the http based dependencies like Volley or even Retrofit and just send the byte data as a multipart http request. it would be much easier and clearer. Or the server cannot communicate using HTTP?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM