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
436 views
in Technique[技术] by (71.8m points)

sockets - Send Image over TCP in android applications

I'm trying to make two android applications connected with TCP protocol. Client has an imageView and when you push the button, it is supposed to send that image to the server and after server reads it, it is suppose to display the image. but I haven't been able to display the sent image in server. somebody could please give me a hand?

THIS IS MY SERVER CODE THAT GETS THE IMAGE AND IT IS SUPPOSE TO DISPLAY IT

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

AND THIS IS MY CLIENT CODE THAT SENDS THE IMAGE

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

            }

        }
    }
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

My code is now working. I'll post the code in case someone finds it helpful

SERVER

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

CLIENT

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

            }

        }
    }

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

...