zoukankan      html  css  js  c++  java
  • android通过socket上传文件

     有两种方式:

    1. 直接将所有数据安装字节数组发送

    2. 对象序列化方式

    Client1 :

    thread方式

    
    package org.lxh.demo;
    
    import java.io.BufferedReader;
    import java.io.ByteArrayOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.ObjectOutputStream;
    import java.net.Socket;
    
    import org.lxh.util.UploadFile;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.os.Environment;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.TextView;
    
    public class MyClientDemo extends Activity {
        private Button send = null;
        private TextView info = null;
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            super.setContentView(R.layout.main);
            this.send = (Button) super.findViewById(R.id.send);
            this.info = (TextView) super.findViewById(R.id.info);
            this.send.setOnClickListener(new SendOnClickListener());
        }
    
        private class SendOnClickListener implements OnClickListener {
            @Override
            public void onClick(View v) {
                try {
                    final Socket client = new Socket("192.168.1.114", 8888);
                    BufferedReader buf = new BufferedReader(new InputStreamReader(
                            client.getInputStream())); // 读取返回的数据
                    new Thread(new Runnable() {
    
                        @Override
                        public void run() {
                            try {
                                ObjectOutputStream oos = new ObjectOutputStream(
                                        client.getOutputStream());
                                UploadFile myFile = SendOnClickListener.this
                                        .getUploadFile();
                                oos.writeObject(myFile);
                                oos.close();
                            } catch (Exception e) {
                            }
                        }
                    }).start();
                    String result = buf.readLine(); // 接收返回信息
                    System.out.println("**************** " + result);
                    if ("true".equals(result)) {
                        MyClientDemo.this.info.setText("操作成功!");
                    } else {
                        MyClientDemo.this.info.setText("操作失败!");
                    }
                    buf.close();
                    client.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
    
            private UploadFile getUploadFile() throws Exception { // 包装了传送数据
                UploadFile myFile = new UploadFile();
                myFile.setTitle("DISNEY公园"); // 设置标题
                myFile.setMimeType("image/jpeg"); // 图片的类型
                File file = new File(Environment.getExternalStorageDirectory()
                        .toString() + File.separator + "disney.jpg");
                InputStream input = null;
                try {
                    input = new FileInputStream(file); // 从文件中读取
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    byte data[] = new byte[1024];
                    int len = 0;
                    while ((len = input.read(data)) != -1) {
                        bos.write(data, 0, len);
                    }
                    myFile.setContentData(bos.toByteArray());
                    myFile.setContentLength(file.length());
                    myFile.setExt("jpg");
                } catch (Exception e) {
                    throw e;
                } finally {
                    input.close();
                }
                return myFile;
            }
    
        }
    
    }
    
    package org.lxh.util;
    
    import java.io.Serializable;
    
    @SuppressWarnings("serial")
    public class UploadFile implements Serializable {
        private String title ;
        private byte [] contentData ;
        private String mimeType ;
        private long contentLength ;
        private String ext ;
        public String getTitle() {
            return title;
        }
        public void setTitle(String title) {
            this.title = title;
        }
        public byte[] getContentData() {
            return contentData;
        }
        public void setContentData(byte[] contentData) {
            this.contentData = contentData;
        }
        public String getMimeType() {
            return mimeType;
        }
        public void setMimeType(String mimeType) {
            this.mimeType = mimeType;
        }
        public long getContentLength() {
            return contentLength;
        }
        public void setContentLength(long contentLength) {
            this.contentLength = contentLength;
        }
        public String getExt() {
            return ext;
        }
        public void setExt(String ext) {
            this.ext = ext;
        }
    }

    Client2:

    handler方式

    
    
    
    package org.lxh.demo;
    
    
    
    import java.io.BufferedReader;
    import java.io.ByteArrayOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.ObjectOutputStream;
    import java.net.Socket;
    
    
    
    import org.lxh.util.UploadFile;
    
    
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.os.Environment;
    import android.os.Handler;
    import android.os.Message;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.TextView;
    
    
    
    public class MyClientDemo extends Activity {
        private Button send = null;
        private TextView info = null;
        private static final int FINISH = 0 ;
        private Handler myHandler = new Handler(){
    
    
    
            @Override
            public void handleMessage(Message msg) {
                switch(msg.what) {
                case FINISH:
                    String result = msg.obj.toString() ;    // 取出数据
                    if ("true".equals(result)) {
                        MyClientDemo.this.info.setText("操作成功!");
                    } else {
                        MyClientDemo.this.info.setText("操作失败!");
                    }
                    break ;
                }
            }
        } ;
    
    
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            super.setContentView(R.layout.main);
            this.send = (Button) super.findViewById(R.id.send);
            this.info = (TextView) super.findViewById(R.id.info);
            this.send.setOnClickListener(new SendOnClickListener());
        }
    
    
    
        private class SendOnClickListener implements OnClickListener {
            @Override
            public void onClick(View v) {
                try {
                    final Socket client = new Socket("192.168.1.114", 8888);
                    final BufferedReader buf = new BufferedReader(new InputStreamReader(
                            client.getInputStream())); // 读取返回的数据
                    new Thread(new Runnable() {
    
    
    
                        @Override
                        public void run() {
                            try {
                                ObjectOutputStream oos = new ObjectOutputStream(
                                        client.getOutputStream());
                                UploadFile myFile = SendOnClickListener.this
                                        .getUploadFile();
                                oos.writeObject(myFile);
                                String str = buf.readLine() ;    // 读取数据
                                oos.close();
                                Message msg = MyClientDemo.this.myHandler
                                        .obtainMessage(FINISH, str);
                                MyClientDemo.this.myHandler.sendMessage(msg) ;
                                buf.close();
                                client.close();
                            } catch (Exception e) {
                                e.printStackTrace() ;
                            }
                        }
                    }).start();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
    
    
    
            private UploadFile getUploadFile() throws Exception { // 包装了传送数据
                UploadFile myFile = new UploadFile();
                myFile.setTitle("DISNEY公园"); // 设置标题
                myFile.setMimeType("image/jpeg"); // 图片的类型
                File file = new File(Environment.getExternalStorageDirectory()
                        .toString() + File.separator + "disney.jpg");
                InputStream input = null;
                try {
                    input = new FileInputStream(file); // 从文件中读取
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    byte data[] = new byte[1024];
                    int len = 0;
                    while ((len = input.read(data)) != -1) {
                        bos.write(data, 0, len);
                    }
                    myFile.setContentData(bos.toByteArray());
                    myFile.setContentLength(file.length());
                    myFile.setExt("jpg");
                } catch (Exception e) {
                    throw e;
                } finally {
                    input.close();
                }
                return myFile;
            }
    
    
    
        }
    
    
    
    }

    Server:

    
    package org.lxh.server;
    
    import java.net.ServerSocket;
    
    public class MyServer {
    
     public static void main(String[] args) throws Exception {
            ServerSocket server = new ServerSocket(8888); // 服务器端端口
            boolean flag = true; // 定义标记,可以一直死循环
            while (flag) { // 通过标记判断循环
                new Thread(new ServerThreadUtil(server.accept())).start(); // 启动线程
            }
            server.close(); // 关闭服务器
        }
    
    }
    
    package org.lxh.server;
    
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.OutputStream;
    import java.io.PrintStream;
    import java.net.Socket;
    import java.util.UUID;
    
    import org.lxh.util.UploadFile;
    
    public class ServerThreadUtil implements Runnable {
        private static final String DIRPATH = "D:" + File.separator + "mldnfile"
                + File.separator; // 目录路径
        private Socket client = null;
        private UploadFile upload = null;
    
        public ServerThreadUtil(Socket client) {
            this.client = client;
            System.out.println("新的客户端连接...");
        }
    
        @Override
        public void run() {
            try {
                PrintStream out = new PrintStream(this.client.getOutputStream());
                ObjectInputStream ois = new ObjectInputStream(
                        client.getInputStream()); // 反序列化
                this.upload = (UploadFile) ois.readObject(); // 读取对象
                System.out.println("文件标题:" + this.upload.getTitle());
                System.out.println("文件类型:" + this.upload.getMimeType());
                System.out.println("文件大小:" + this.upload.getContentLength());
                out.print(this.saveFile()) ;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    this.client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    
        private boolean saveFile() throws Exception { // 负责文件内容的保存
            File file = new File(DIRPATH + UUID.randomUUID() + "."
                    + this.upload.getExt());
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdir();
            }
            OutputStream output = null;
            try {
                output = new FileOutputStream(file) ;
                output.write(this.upload.getContentData()) ;
                return true ;
            } catch (Exception e) {
                throw e;
            } finally {
                output.close();
            }
        }
    }
    
    package org.lxh.util;
    
    import java.io.Serializable;
    
    @SuppressWarnings("serial")
    public class UploadFile implements Serializable {
        private String title ;
        private byte [] contentData ;
        private String mimeType ;
        private long contentLength ;
        private String ext ;
        public String getTitle() {
            return title;
        }
        public void setTitle(String title) {
            this.title = title;
        }
        public byte[] getContentData() {
            return contentData;
        }
        public void setContentData(byte[] contentData) {
            this.contentData = contentData;
        }
        public String getMimeType() {
            return mimeType;
        }
        public void setMimeType(String mimeType) {
            this.mimeType = mimeType;
        }
        public long getContentLength() {
            return contentLength;
        }
        public void setContentLength(long contentLength) {
            this.contentLength = contentLength;
        }
        public String getExt() {
            return ext;
        }
        public void setExt(String ext) {
            this.ext = ext;
        }
    }
  • 相关阅读:
    【leetcode】1442. Count Triplets That Can Form Two Arrays of Equal XOR
    【leetcode】1441. Build an Array With Stack Operations
    【leetcode】1437. Check If All 1's Are at Least Length K Places Away
    cxCheckCombobox
    修改现有字段默认值
    2018.01.02 exprottoexcel
    Statusbar OwnerDraw
    dxComponentPrinter记录
    单据暂存操作思路整理
    设置模式9(装饰者,责任链,桥接,访问者)
  • 原文地址:https://www.cnblogs.com/itfanr/p/3161192.html
Copyright © 2011-2022 走看看