Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
146 views
in Technique[技术] by (71.8m points)

java - TCP SOCKET image transfering

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() + "
";
                        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,[email protected],>");

                    }
*/
                    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,[email protected],>");

                    }
                    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 + "

");
                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);
                    } c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...