安卓:图像接收到插座损坏 [英] Android: Image received over socket is corrupted

查看:126
本文介绍了安卓:图像接收到插座损坏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好这里有一个问题:服务器正确地发送图像到客户端(我认为)。从客户端接收的文件是​​在服务器手机上的文件present大小相同,所以每个字节得到转移我猜,但仍然图像是不可见的。无论是服务器和客户端的Andr​​oid手机。在此先感谢,我希望你能帮助我。

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.

服务器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();
     }
}

}

客户端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();
            }
        }
    }    

}

推荐答案

您正在结合缓冲,并在同一个底层流无缓冲I / O。缓冲的读者将填充其缓冲区与任何可窃取其他数据流。你有数据输入和输出流:使用他们的一切。您可以通过writeInt()/的readInt()发送的文件大小。

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().

这篇关于安卓:图像接收到插座损坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆