TCP SOCKET 图像传输

问题描述

我正在尝试通过 tcp 套接字发送 .yuv 图像文件,但传输了一些字节数组和图像构建,但没有获得 100% 图像,它只显示 10% 的图像。我使用异步任务在服务器端连续接收图像数据。

这里是服务器端代码

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() + "\r\n";
                        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,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,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,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("<,>");

                    }
                    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 + "\n\r");
                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,c,buf.length);
                    System.arraycopy(b1,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,yuvImage.getWidth(),yuvImage.getHeight()),100,out);
                byte[] imageBytes = out.toByteArray();
                Bitmap image = BitmapFactory.decodeByteArray(imageBytes,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();
    }
}

客户端代码

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,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 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]);
        }
    }


}

[我第一次发送图像时得到这个输出0

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)