Android: Image received over socket is corrupted

梦想与她 提交于 2019-12-04 06:10:00

问题


Hi here's the problem: the server sends the image to the client correctly ( I think ). The file received from the client is the same size of the file present on the server phone, so every byte got transferred I guess but still the image is not visible. Either the server and the client are android phones. Thanks in advance I hope you can help me.

Server code:

public class FileActivity extends Activity {

private FileInputStream fileInputStream;
private BufferedInputStream bufferedInputStream;
private OutputStream outputStream;

private byte [] mybytearray;

private String tmp = null;

private TextView tv;

private File myFile;

private int l;

private String path;

private EditText editText;

private ServerSocket serverSocket;

private Socket client;

public static String SERVERIP = "10.0.2.15";

private final int SERVERPORT = 8080;

private byte [] imgbyte;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_file);

    tv = (TextView) findViewById(R.id.textView1);
    editText = (EditText) findViewById(R.id.editText1);

    SERVERIP = getLocalIpAddress();

    Thread sThread = new Thread(new ServerThread());
    sThread.start();
}

public void sendListener(View v) {

    tmp = editText.getText().toString();

    path = "/sdcard/" + tmp;

    myFile = new File(path);Log.d("SERVER", "WORKS");           

    l = (int) myFile.length();Log.d("SERVER", "WORKS");

    tv.setText(path + "  " + Integer.toString(l));  

    tmp = Integer.toString(l);  Log.d("SERVER", "WORKS");

    String test = tmp;



    //out.println(tmp);
    Log.d("SERVER", "WORKS");
    try {

        PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())), true);
        out.println(test);
        //out.close();
        Log.d("SERVER", "WORKS");
        byte[] mybytearray = new byte[1024]; //create a byte array to file
        Log.d("SERVER", "WORKS");
        fileInputStream = new FileInputStream(myFile);
         bufferedInputStream = new BufferedInputStream(fileInputStream);  
         Log.d("SERVER", "WORKS");


         Log.d("SERVER", "WORKS");
         try{
             outputStream = client.getOutputStream();
         } catch(Exception e)
         {
             Log.d("OUTPUT", "UFFFF");
             e.printStackTrace();
         }
        /* Log.d("SERVER", "ALMOST");
         outputStream.write(mybytearray, 0, mybytearray.length); Log.d("SERVER", "DONE");//write file to the output stream byte by byte*/
      //  outputStream.flush();
       // outputStream.close();

         Log.d("SERVER", "WORKS");
         int count = 0;
         int size = 0;

         while((count = bufferedInputStream.read(mybytearray, 0 , mybytearray.length)) != -1)
         {
            // count = bufferedInputStream.read(mybytearray, 0 , mybytearray.length);
             size += count;
             Log.d("SERVER", "SEND");
             try{
                 outputStream.write(mybytearray, 0, count);
             } catch(Exception e) {
                 e.printStackTrace();
             }

             Log.d("TEST", Integer.toString(count));
         }
         Log.d("SERVER", "DONE");
         bufferedInputStream.close();
         outputStream.close();
               client.close();
    } catch (Exception e) {

    }   


}


public class ServerThread implements Runnable {

    @Override
    public void run() {
        // TODO Auto-generated method stub
        try {
            serverSocket = new ServerSocket(SERVERPORT);
            client = serverSocket.accept();
            //outputStream = client.getOutputStream();

            Log.d("SERVER", "Connesso");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Log.d("TEST", "UFFFAAA");
        }           
    }

}

private String getLocalIpAddress() {

    String tmp = "";

    int i = 0;

    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()) 
                { 

                    tmp += "IP: " + inetAddress.getHostAddress() + "\n"; 

                }
            }
        }
    } catch (SocketException ex) {
        Log.e("ServerActivity", ex.toString());
    }
    return tmp;
}

@Override
protected void onStop() {
    super.onStop();
    try {
         serverSocket.close();
     } catch (IOException e) {
         e.printStackTrace();
     }
}

}

Client code:

public class FileActivity extends Activity {

private EditText serverIp, getPort;
private Button connectPhones;
private TextView tv, tvIP;

private Boolean connected = false;

private String serverIpAddress, portStr;

private Socket socket;

private int port, len;

private String filepath;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_file);

    tvIP = (TextView) findViewById(R.id.IPtv);
    tv = (TextView) findViewById(R.id.Portatv);
    serverIp = (EditText) findViewById(R.id.server_ip);
    connectPhones = (Button) findViewById(R.id.connect_phones);
    getPort = (EditText) findViewById(R.id.server_port); 
}

public void connectListener(View v)
{
    if (!connected) {
        serverIpAddress = serverIp.getText().toString();
        portStr = getPort.getText().toString();
        if (!serverIpAddress.equals("")) {
            Thread cThread = new Thread(new ClientThread());
            cThread.start();
        }
    }
}

public class ClientThread implements Runnable
{
    @Override
    public void run() {
        // TODO Auto-generated method stub
        port = Integer.parseInt(portStr);

        socket = new Socket();

        try {
            InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
            Log.d("ClientActivity", "C: Connessione in corso...");
            socket = new Socket(serverAddr, port);
            Log.d("ClientActivity", "C: Connesso!");
            connected = true;

            DataInputStream dis;
            try {
                dis = new DataInputStream(socket.getInputStream());
                int bytes;
                byte[] b = new byte[32];
                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String l = in.readLine();
                //String line = Integer.toString(l);
                Log.d("PROVA", l);  
                try
                {
                    len = Integer.parseInt(l); Log.d("CLIENT", Integer.toString(len));
                }
                catch (NumberFormatException e)
                {
                    e.printStackTrace();
                }
                byte[] img = new byte[1082922];  //1082922
                FileOutputStream fos = new FileOutputStream("/sdcard/img.jpg");
                BufferedOutputStream bos = new BufferedOutputStream(fos);

                /*bytes = dis.read(img, 0, img.length);

                bos.write(img, 0, img.length);*/
                int count = 0;
                while ((bytes = dis.read(img)) != -1) {
                    count += bytes;
                    Log.d("CLIENT", Integer.toString(count));
                    Log.d("TEST", Integer.toString(bytes));
                    //Write to file
                    bos.write(img, 0, bytes);
                }
                bos.flush();
                bos.close();
                Log.d("TCP", "Save to file");
            } catch(IOException e){
                e.printStackTrace();
            }                

        } catch (Exception e) {
            Log.e("ClientActivity", "C: Errore", e);
            connected = false;
        }
    }

}

 @Override
    protected void onStop() {
        super.onStop();
        if(connected == true)
        {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }    

}


回答1:


You're combining buffered and unbuffered I/O on the same underlying streams. The buffered reader will steal data from the other stream by filling its buffer with whatever is available. You have data input and output streams: use them for everything. You can send the file size via writeInt()/readInt().




回答2:


You have already one .read() before the while loop. And those bytes you do not write() so the client does not receive the first bytes of the file. O i see now that you write them but do not count them in size. Anyhow: bad construction. And for the first read you should have used a count variable too. And write only count bytes. Better remove the first read completely.



来源:https://stackoverflow.com/questions/24418656/android-image-received-over-socket-is-corrupted

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!