android开发 socket接收图片并保存

逻辑:接收到socket之后需要将socket发送的图片数据保存下来并通知handler更新界面

关键代码:

public void readImage(Socket socket) 
        {
            try
            {
                InputStream in = socket.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(in);
                Bitmap bitmap = BitmapFactory.decodeStream(bis);//这个好像是android里的 
                //首先看看文件是否存在
                File f = new File(mfilePath);
                File bmpFile = new File(mfilePath, "screen.png");
                if (!f.exists()) {
                    f.mkdirs();
                }
                if (bmpFile.exists()) {
                    bmpFile.delete();
                }
                FileOutputStream out = new FileOutputStream(bmpFile);
                bitmap.compress(Bitmap.CompressFormat.PNG, 100,out);
                bis.close();
                in.close();
                
            }
            catch(Exception ex)
            {
                Log.v(TAG, ex.getMessage());
                
            }
            finally
            {
                Message msg = new Message();
                msg.what = 1;  //说明有图片更新
                mHandler.sendMessage(msg);
                Log.v(TAG, "接收到图片,准备handler消息更新界面");
                release();
            }
        }


服务器端socket接收所有代码:

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

/**
 * 服务器端完整socket接收代码(接收客户端的图片)
 * @author huqiang
 *
 */
public class SocketService implements Runnable{
    private static final String TAG = "SZU_TcpService";

    private ServerSocket serviceSocket;
    private boolean SCAN_FLAG = false; // 接收扫描标识
    private boolean REV_FLAG = false; // 接收标识
    
    private static String mfilePath = null; // 存放接收文件的路径

    private static Context mContext;
    private static SocketService instance; // 唯一实例
    private Thread mThread;
    private boolean IS_THREAD_STOP = false; // 是否线程开始标志

    private static Handler mHandler;
    public SocketService()
    {
        try
        {
            serviceSocket = new ServerSocket(4700);
            Log.d(TAG, "建立监听服务器ServerSocket成功");
        } catch (IOException e)
        {
            Log.d(TAG, "建立监听服务器ServerSocket失败");
            e.printStackTrace();
        }
        mThread = new Thread(this);
    }

    /**
     * <p>
     * 获取TcpService实例
     * <p>
     * 单例模式,返回唯一实例
     */
    public static SocketService getInstance(Context context,Handler handler,String filepath)
    {
        mContext = context;
        mHandler = handler;
        mfilePath = filepath;
        if (instance == null)
        {
            instance = new SocketService();
        }
        return instance;
    }

    public void setSavePath(String fileSavePath)
    {
        Log.d(TAG, "设置存储路径成功,路径为" + fileSavePath);
        this.mfilePath = fileSavePath;
        // REV_FLAG=true;
    }

    public SocketService(Context context)
    {
        this();
        mContext = context;
    }

    private void scan_recv()
    {
        try
        {
            Socket socket = serviceSocket.accept(); // 接收UDP数据报
//            socket.setSoTimeout(10*1000); // 设置掉线时间
            Log.d(TAG, "客户端连接成功");
            //通过子线程来循环读取socket的消息
            ListenClientSocket ls = new ListenClientSocket(socket);
            ls.start();

        } catch (IOException e)
        {
            e.printStackTrace();
            Log.d(TAG, "客户端连接失败");
            SCAN_FLAG = false;
        }
    }

    @Override
    public void run()
    {
        Log.d(TAG, "TCP_Service线程开启");
        while (!IS_THREAD_STOP)
        {
            if (SCAN_FLAG)
            {
                scan_recv();
            }
        }
    }

    public void release()
    {
        if (null != serviceSocket && !serviceSocket.isClosed())
            try
            {
                serviceSocket.close();
                serviceSocket = null;
                Log.d(TAG, "关闭socket成功");
            } catch (IOException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        while (SCAN_FLAG == true)
            ;// 直到SCAN_FLAG为false的时候退出循环
        SCAN_FLAG = false;
        IS_THREAD_STOP = true;
    }

    public void startReceive()
    {
        SCAN_FLAG = true; // 使能扫描接收标识
        if (!mThread.isAlive())
            mThread.start(); // 开启线程
    }

    public void stopReceive()
    {
        while (SCAN_FLAG == true)
            ;
        SCAN_FLAG = false; // 失能扫描接收标识
    }
    
    /**
     * 监听客户端发送的消息
     * @author huqiang
     *
     */
    class ListenClientSocket implements Runnable
    {
        private boolean IsListening = false;
        private Socket clientSocket;
        private Thread thread;
        public ListenClientSocket(Socket s)
        {
            this.clientSocket = s;
            this.thread = new Thread(this);
        }
        @Override
        public void run() {
            while(clientSocket!=null&&!clientSocket.isClosed()&&IsListening)
            {
                readImage(this.clientSocket);
            }
        }
        public void start()
        {
            IsListening = true;
            thread.start();
        }
        public void release()
        {
            IsListening = false;
            if(!clientSocket.isClosed())
            {
                try {
                    clientSocket.close();
                    clientSocket = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                
            }
        }
        public void readImage(Socket socket) 
        {
            try
            {
                InputStream in = socket.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(in);
                Bitmap bitmap = BitmapFactory.decodeStream(bis);//这个好像是android里的 
                //首先看看文件是否存在
                File f = new File(mfilePath);
                File bmpFile = new File(mfilePath, "screen.png");
                if (!f.exists()) {
                    f.mkdirs();
                }
                if (bmpFile.exists()) {
                    bmpFile.delete();
                }
                FileOutputStream out = new FileOutputStream(bmpFile);
                bitmap.compress(Bitmap.CompressFormat.PNG, 100,out);
                bis.close();
                in.close();
                
            }
            catch(Exception ex)
            {
                Log.v(TAG, ex.getMessage());
                
            }
            finally
            {
                Message msg = new Message();
                msg.what = 1;  //说明有图片更新
                mHandler.sendMessage(msg);
                Log.v(TAG, "接收到图片,准备handler消息更新界面");
                release();
            }
        }
        
    }
}

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。