【问题标题】:Send Image over TCP in android applications在 Android 应用程序中通过 TCP 发送图像
【发布时间】:2014-08-07 18:24:09
【问题描述】:

我正在尝试使两个 android 应用程序与 TCP 协议连接。 客户端有一个 imageView,当您按下按钮时,它应该将该图像发送到服务器,并且在服务器读取它之后,它应该显示该图像。 但我无法在服务器中显示发送的图像。 有人可以帮帮我吗?

这是获取图像的我的服务器代码,应该显示它

        package com.example.simpleserver;

    import java.io.DataInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.ServerSocket;
    import java.net.Socket;

    import android.app.Activity;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Message;
    import android.widget.ImageView;
    import android.widget.TextView;

     public class SimpleServer extends Activity {
       ServerSocket ss = null;
       Thread myCommsThread = null;
       protected static final int MSG_ID = 0x1337;
       public static final int SERVERPORT = 6000;
       private Bitmap bitmap;

       @Override
      public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_simple_server);
       TextView tv = (TextView) findViewById(R.id.textView01);
       tv.setText("Nothing from client yet");
       this.myCommsThread = new Thread(new CommsThread());
       this.myCommsThread.start();
       }

       @Override
       protected void onStop() {
       super.onStop();
       try {
            // make sure you close the socket upon exiting
           ss.close();
        } catch (IOException e) {
           e.printStackTrace();
        }
       }

       Handler myUpdateHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_ID:
                     ImageView tv = (ImageView) findViewById(R.id.imageViewServer);
                     tv.setImageBitmap(bitmap);
                     break;
                   default:
                       break;
                   }
             super.handleMessage(msg);
         }
      };
       class CommsThread implements Runnable {
        public void run() {
           Socket s = null;
            try {
            ss = new ServerSocket(SERVERPORT );
        } catch (IOException e) {
            e.printStackTrace();
        }
        while (!Thread.currentThread().isInterrupted()) {
            Message m = new Message();
            m.what = MSG_ID;

            try {
                if (s == null)
                    s = ss.accept();
                InputStream in = s.getInputStream();
                DataInputStream dis = new DataInputStream(in);

                int len = dis.readInt();
                byte[] data = new byte[len];
                if (len > 0) {
                    dis.readFully(data);
                }
                bitmap = BitmapFactory.decodeByteArray(data , 0, data .length);
                myUpdateHandler.sendMessage(m);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    }
    }

这是我发送图像的客户代码

        package com.example.simpleclient;

    import java.io.DataOutputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.net.InetAddress;
    import java.net.Socket;
    import java.net.UnknownHostException;
    import java.nio.ByteBuffer;

    import android.app.Activity;
    import android.graphics.Bitmap;
    import android.graphics.drawable.BitmapDrawable;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.ImageView;

    public class SimpleClient extends Activity {

        private Socket socket;

        private static final int SERVERPORT = 5000;
        private static final String SERVER_IP = "10.0.2.2";

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_simple_client);        
            new Thread(new ClientThread()).start();
        }

        public void onClick(View view) {
            try {;
                getBytes();

            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        public void getBytes() throws IOException{
            ImageView iv=(ImageView)findViewById(R.id.imageView1);
            //convert the image to bitmap to be send in the intent
            Bitmap bmp=((BitmapDrawable)iv.getDrawable()).getBitmap();
            int bytes = bmp.getByteCount();
            ByteBuffer buffer = ByteBuffer.allocate(bytes); //Create a new buffer
            bmp.copyPixelsToBuffer(buffer); //Move the byte data to the buffer

            byte[] array = buffer.array(); 
            int start=0;
            int len=array.length;
            if (len < 0)
                throw new IllegalArgumentException("Negative length not allowed");
            if (start < 0 || start >= array.length)
                throw new IndexOutOfBoundsException("Out of bounds: " + start);

            OutputStream out = socket.getOutputStream(); 
            DataOutputStream dos = new DataOutputStream(out);

            dos.writeInt(len);
            if (len > 0) {
                dos.write(array, start, len);
            }

        }

        class ClientThread implements Runnable {

            @Override
            public void run() {

                try {
                    InetAddress serverAddr = InetAddress.getByName(SERVER_IP);

                    socket = new Socket(serverAddr, SERVERPORT);

                } catch (UnknownHostException e1) {
                    e1.printStackTrace();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }

            }

        }
    }

【问题讨论】:

  • 那么它有多远?客户端是否连接?是否发送位图?是否收到位图?你必须告诉我们。您可以添加一些日志语句,以便查看发生了什么。没有错误?您检查发送的 len 和接收的 len 是否相等?
  • 连接没有问题,也没有显示错误。问题似乎出在服务器中,同时尝试将接收到的字节数组转换为位图,我得到位图为空。有人知道将字节数组转换为位图的最佳方法吗?
  • 发送的len和收到的len一样吗?为什么我要问两次?
  • 是的,它与收到的 len 相同。问题接缝在这里:bitmap = BitmapFactory.decodeByteArray(data , 0, data .length);
  • 在您的客户端中,您终于有了字节[] 数组中的位图。您是否尝试在您的客户端中立即将其转换回位图并在 ImageView 中显示?如果你没有,那么首先尝试一下。您将 Bi​​tmap 转换为 byte[] 的方式与我所知道的不同。

标签: android sockets tcp


【解决方案1】:

尝试使用以下代码将图像放入字节数组中:

     ImageView iv=(ImageView)findViewById(R.id.imageView);
     Bitmap bmp=((BitmapDrawable)iv.getDrawable()).getBitmap();

     ByteArrayOutputStream baos = new ByteArrayOutputStream();
     bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
     byte array [] = baos.toByteArray();

此外,我必须指出,您在主线程上执行 getBytes()。这仅适用于较旧的 Android 版本。最好把它放在你的线程中。

【讨论】:

    【解决方案2】:

    我的代码现在可以工作了。我会发布代码以防有人发现它有帮助

    服务器

        package com.example.serverlate;
        import java.io.BufferedReader;
        import java.io.ByteArrayOutputStream;
        import java.io.DataInputStream;
        import java.io.IOException;
        import java.io.InputStream;
        import java.io.InputStreamReader;
        import java.net.ServerSocket;
        import java.net.Socket;
    
        import android.app.Activity;
        import android.graphics.Bitmap;
        import android.graphics.BitmapFactory;
        import android.os.Bundle;
        import android.os.Handler;
        import android.util.DisplayMetrics;
        import android.widget.ImageView;
        import android.widget.TextView;
    
        public class ServerLate extends Activity {
    
            private ServerSocket serverSocket;
    
            Handler updateConversationHandler;
    
            Thread serverThread = null;
    
    
            private ImageView imageView;//  private TextView text;
    
            public static final int SERVERPORT = 6000;
    
            @Override
            public void onCreate(Bundle savedInstanceState) {
    
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_server_late);
    
    
                imageView=(ImageView) findViewById(R.id.imageViewServer);//text = (TextView) findViewById(R.id.textView01); 
    
                updateConversationHandler = new Handler();
    
                this.serverThread = new Thread(new ServerThread());
                this.serverThread.start();
    
            }
    
            @Override
            protected void onStop() {
                super.onStop();
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    
            class ServerThread implements Runnable {
    
                public void run() {
                    Socket socket = null;
                    try {
                        serverSocket = new ServerSocket(SERVERPORT);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    while (!Thread.currentThread().isInterrupted()) {
    
                        try {
    
                            socket = serverSocket.accept();
    
                            CommunicationThread commThread = new CommunicationThread(socket);
                            new Thread(commThread).start();
    
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
    
            class CommunicationThread implements Runnable {
    
                private Socket clientSocket;
    
                private DataInputStream input;//private BufferedReader input;       
    
                public CommunicationThread(Socket clientSocket) {
    
                    this.clientSocket = clientSocket;
    
                    try {
    
                        //this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
    
                        InputStream in = this.clientSocket.getInputStream();
                        this.input = new DataInputStream(in);               
    
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
    
                public void run() {
                    System.out.println("hello");
                    while (!Thread.currentThread().isInterrupted()) {
                        try {
                            byte[] data;//String read = input.readLine();
                            int len= this.input.readInt();                  
                            data = new byte[len];                   
                            if (len > 0) {
                                this.input.readFully(data,0,data.length);
                            }   
                            /*
                            ByteArrayOutputStream out = new ByteArrayOutputStream();
                            byte[] data;
                            int length = 0;
                            while ((length = this.input.read(data))!=-1) {
                                out.write(data,0,length);
                            }
                               data=out.toByteArray();
                            */
    
                            updateConversationHandler.post(new updateUIThread(data));//updateConversationHandler.post(new updateUIThread(read));
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
    
            }
    
            class updateUIThread implements Runnable {
                private byte[] byteArray;//private String msg;
    
                public updateUIThread(byte[] array){    //public updateUIThread(String str) {
                    this.byteArray=array;   //this.msg = str;
                }
    
                @Override
                public void run() { 
                    Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray , 0, byteArray .length);
                    imageView.setImageBitmap(bitmap);//text.setText(text.getText().toString()+"Client Says: "+ msg + "\n");
                }
            }
        }
    

    客户

        package com.example.clientlate;
    
        import java.io.BufferedWriter;
        import java.io.ByteArrayOutputStream;
        import java.io.DataOutputStream;
        import java.io.IOException;
        import java.io.OutputStream;
        import java.io.OutputStreamWriter;
        import java.io.PrintStream;
        import java.io.PrintWriter;
        import java.net.InetAddress;
        import java.net.Socket;
        import java.net.UnknownHostException;
        import java.nio.ByteBuffer;
    
        import android.app.Activity;
        import android.graphics.Bitmap;
        import android.graphics.BitmapFactory;
        import android.graphics.Bitmap.CompressFormat;
        import android.graphics.drawable.BitmapDrawable;
        import android.os.Bundle;
        import android.util.DisplayMetrics;
        import android.view.View;
        import android.widget.EditText;
        import android.widget.ImageView;
    
        public class ClientLate extends Activity {
    
            private Socket socket;
    
            private static final int SERVERPORT = 5000;
            private static final String SERVER_IP = "10.0.2.2";
    
            @Override
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_client_late);      
    
                new Thread(new ClientThread()).start();
            }
    
            public void onClick(View view) {
                try {           
                    ImageView imageView=(ImageView) findViewById(R.id.imageView1);//EditText et = (EditText) findViewById(R.id.EditText01);
                    Bitmap bmp=((BitmapDrawable)imageView.getDrawable()).getBitmap(); //String str = et.getText().toString();
    
                    ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
                    bmp.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, bos); 
                    byte[] array = bos.toByteArray();
    
                    OutputStream out = socket.getOutputStream(); 
                    DataOutputStream dos = new DataOutputStream(out);
                    dos.writeInt(array.length);
                    dos.write(array, 0, array.length);
    
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
    
            class ClientThread implements Runnable {
    
                @Override
                public void run() {
    
                    try {
                        InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
    
                        socket = new Socket(serverAddr, SERVERPORT);
    
                    } catch (UnknownHostException e1) {
                        e1.printStackTrace();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
    
                }
    
            }
        }
    

    【讨论】:

    • 你说得对,我更正了。打扰一下,您知道如何在 C++ 服务器中检索图像吗? stackoverflow.com/questions/24541205/…
    • 快速浏览了一下。所以你想要一个在 Android 上运行的 TCP 服务器?用 QT C++ 编写?
    • 不,我有一个在 android 上运行的 java 编写的客户端,我的服务器是 qt c++。
    • 这不是我问题的答案。请仔细阅读并回答问题。这两个问题都可以用是/否来回答。
    猜你喜欢
    • 1970-01-01
    • 2014-01-16
    • 1970-01-01
    • 2015-03-02
    • 1970-01-01
    • 2017-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多