1. 程式人生 > >Android Socket 實現批量圖片傳輸

Android Socket 實現批量圖片傳輸

        實現的原理其實也不難,苦於網上沒有現成的例子,所以就自己實現了一個。就是在socket 進行圖片資料傳輸的時候,自己去構建一個數據頭header ,然後另外一端在讀取資料的時候,以這個資料頭"start-xxxx"為依據實現image 影象的byte 資料讀取。然後解析出來。本例子是實現1s 傳送一次read 請求。 

package com.example.zhouyong0701.socketcommtest;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private Button btnServer;
    private Button btnClient;

    private Socket mClient;
    private ServerSocket mServer;
    private Bitmap mBitmap;
    private Handler mHander = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if(msg.what == 0x123) {
                ((ImageView)findViewById(R.id.image)).setImageBitmap(mBitmap);
            }
            super.handleMessage(msg);
        }
    };

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

        btnServer = (Button) findViewById(R.id.server);
        btnClient = (Button) findViewById(R.id.client);
        btnServer.setOnClickListener(this);
        btnClient.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.server) {
            Log.d("zhouyong","server button is click ....");
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        mServer = new ServerSocket(5800);
                        Log.d("zhouyong","server is waiting ....");
                        Socket socket = mServer.accept();
                        InputStream in = socket.getInputStream();
                        DataInputStream din = new DataInputStream(in);
                        OutputStream outputStream = socket.getOutputStream();
                        Log.d("zhouyong", "server is connected ....");
                        while(true) {
                            Log.d("zhouyong", "server send cmd ....");
                            outputStream.write("read\n".getBytes());
                            outputStream.flush();
                            int imagesize = 0;
                            if (socket.isConnected()) {
                                Log.d("zhouyong", "server read start ....");
                                //image data header
                                byte[] header = new byte[14];
                                int len;
                                while((len = din.read(header,0,header.length)) > 0) {
                                    String str = new String(header);
                                    if(str.startsWith("start")) {
                                        imagesize = Integer.parseInt(str.split("-")[1]);
                                        Log.d("zhouyong", "server header str = " + str +" size = "+imagesize);
                                        break;
                                    }
                                }
                                byte[] data = new byte[imagesize];
                                len = din.read(data,0,data.length);
                                Log.d("zhouyong", "server read successs size = "+len);
                                if(len > 0 ){
                                    mBitmap = BitmapFactory.decodeByteArray(data,0,data.length);
                                    mHander.sendEmptyMessage(0x123);
                                }
                            }
                            Thread.sleep(1000);
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        } else {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        mClient = new Socket("127.0.0.1", 5800);
                        Log.d("zhouyong","connected ...");
                        OutputStream out = mClient.getOutputStream();
                        DataOutputStream dout = new DataOutputStream(out);
                        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(mClient.getInputStream()));
                        String cmd;
                        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.test1);
                        Bitmap bitmap1 = BitmapFactory.decodeResource(getResources(), R.drawable.test2);
                        boolean flag = true;
                        while (true) {
                            cmd = bufferedReader.readLine();
                            Log.d("zhouyong","client cmd = "+cmd);
                            if ("read".equals(cmd)) {
                                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                                if(flag) {
                                    bitmap.compress(Bitmap.CompressFormat.JPEG, 20, bout);
                                } else {
                                    bitmap1.compress(Bitmap.CompressFormat.JPEG, 20, bout);
                                }
                                bout.flush();
                                Log.d("zhouyong", "send cap jpg ...bout.size() = " + bout.size());
                                int size = bout.size();
                                String header = String.format("start-%08d",size);
                                Log.d("zhouyong","header = "+header+" size = "+header.getBytes().length);
                                dout.write(header.getBytes());
                                dout.write(bout.toByteArray());
                                dout.flush();
                                flag = !flag;
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }
}