Android 用Socket实现PC和手机的文件传输

PC服务器端代码:

/*
 * PC与http://lib.csdn.net/base/android" class='replace_word' title="Android知识库" target='_blank' style='color:#df3434; font-weight:bold;'>Android客户端实现文件的传送
 * PC服务器端
 */
package com."http://lib.csdn.net/base/android" class='replace_word' title="Android知识库" target='_blank' style='color:#df3434; font-weight:bold;'>android.test;
import "http://lib.csdn.net/base/java" class='replace_word' title="Java 知识库" target='_blank' style='color:#df3434; font-weight:bold;'>Java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java"http://lib.csdn.net/base/dotnet" class='replace_word' title=".NET知识库" target='_blank' style='color:#df3434; font-weight:bold;'>.NET.ServerSocket;
import java"http://lib.csdn.net/base/dotnet" class='replace_word' title=".NET知识库" target='_blank' style='color:#df3434; font-weight:bold;'>.net.Socket;
public class TransferFileServer {
    private static final int HOST_PORT = 8821;
    private void start() {
        Socket s = null;
        try {
            ServerSocket ss = new ServerSocket(HOST_PORT);
            while (true) {
                String filePath = "/home/fan/Pictures/1.jpg";
                File file = new File(filePath);
                System.out.println("文件长度:" + (int) file.length());
                s = ss.accept();
                log("建立Socket连接");
                DataInputStream dis = new DataInputStream(
                        new BufferedInputStream(s.getInputStream()));
                dis.readByte();
                DataInputStream fis = new DataInputStream(
                        new BufferedInputStream(new FileInputStream(filePath)));
                DataOutputStream dos = new DataOutputStream(s.getOutputStream());
                dos.writeUTF(file.getName());
                dos.flush();
                dos.writeLong((long) file.length());
                dos.flush();
                int bufferSize = 8192;
                byte[] buf = new byte[bufferSize];
                while (true) {
                    int read = 0;
                    if (fis != null) {
                        read = fis.read(buf);
                    }
                    if (read == -1) {
                        break;
                    }
                    dos.write(buf,0,read);
                }
                dos.flush();
                 // 注意关闭socket链接哦,不然客户端会等待server的数据过来,
                // 直到socket超时,导致数据不完整。
                fis.close();
                s.close();
                log("文件传输完成");
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    void log(String msg) {
        System.out.println(msg);
    }
    public static void main(String args[]) {
        new TransferFileServer().start();
    }
}

ClientSocket:辅助类

/*
 * PC与Android文件传输
 * Android客户端
 */
package com.android.test;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java"http://lib.csdn.net/base/dotnet" class='replace_word' title=".NET知识库" target='_blank' style='color:#df3434; font-weight:bold;'>.Net.Socket;
import java.net.UnknownHostException;
public class ClientSocket {
    private String ip;
    private int port;
    private Socket socket = null;
    DataOutputStream out = null;
    DataInputStream getMessageStream = null;
    public ClientSocket(String ip, int port) {
        this.ip = ip;
        this.port = port;
    }
    public void createConnection() {
        try {
            socket = new Socket(ip, port);
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        } finally {
        }
    }
    public void sendMessage(String sendMessage) {
        try {
            out = new DataOutputStream(socket.getOutputStream());
            if (sendMessage.equals("Windows")) {
                out.writeByte(0x1);
                out.flush();
                return;
            }
            if (sendMessage.equals("Unix")) {
                out.writeByte(0x2);
                out.flush();
                return;
            }
            if (sendMessage.equals(""http://lib.csdn.net/base/linux" class='replace_word' title="Linux知识库" target='_blank' style='color:#df3434; font-weight:bold;'>Linux")) {
                out.writeByte(0x3);
                out.flush();
            } else {
                out.writeUTF(sendMessage);
                out.flush();
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        }
    }
    public DataInputStream getMessageStream() {
        try {
            getMessageStream = new DataInputStream(new BufferedInputStream(
                    socket.getInputStream()));
            // return getMessageStream;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            if (getMessageStream != null) {
                try {
                    getMessageStream.close();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        }
        return getMessageStream;
    }
    public void shutDownConnection() {
        try {
            if (out != null) {
                out.close();
            }
            if (getMessageStream != null) {
                getMessageStream.close();
            }
            if (socket != null) {
                socket.close();
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Android客户端:Acitivyt实现:

package com.android.test;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Main extends Activity implements OnClickListener{
    private ClientSocket cs = null;
    private static final String FILE_PATH = "/mnt/sdcard/";
    private String ip = "192.168.1.103";
    private int port = 8821;
    private String sendMessage = ""http://lib.csdn.net/base/linux" class='replace_word' title="Linux知识库" target='_blank' style='color:#df3434; font-weight:bold;'>linux";
    private Button mButton;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mButton = (Button)findViewById(R.id.start);
        mButton.setOnClickListener(this);
    }
    private void start() {
        if (createConnection()) {
            sendMessage();
            getMessage();
        }
    }
    private void getMessage() {
        if (cs == null)
            return;
        DataInputStream inputStream = null;
        inputStream = cs.getMessageStream();
        try {
            String savePath = FILE_PATH;
            int bufferSize = 8192;
            byte[] buf = new byte[bufferSize];
            int passedlen = 0;
            long len = 0;
            
            savePath += inputStream.readUTF();
            Log.d("AndroidClient","@@@savePath"+savePath);
            DataOutputStream fileOut = new DataOutputStream(
                    new BufferedOutputStream(new BufferedOutputStream(
                            new FileOutputStream(savePath))));
            len = inputStream.readLong();
            Log.d("AndoridClient","文件的长度为:"+len);
            Log.d("AndroidClient","开始接收文件");
            while(true) {
                int read = 0;
                if (inputStream != null) {
                    read = inputStream.read(buf);
                }
                passedlen += read;
                if (read == -1) {
                    break;
                }
                Log.d("AndroidClient","文件接收了"+(passedlen*100/len)+"%/n");
                fileOut.write(buf,0,read);
            }
            Log.d("AndroidClient","@@@文件接收完成"+savePath);
            fileOut.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    private void sendMessage() {
        if (cs == null)
            return;
        cs.sendMessage(sendMessage);
    }
    private boolean createConnection() {
        cs = new ClientSocket(ip, port);
        cs.createConnection();
        Log.d("Main", "连接服务器成功:");
        return true;
    }
    public void onClick(View v) {
        start();
    }
}

 

转载于:https://www.cnblogs.com/zhujiabin/p/7143739.html

你可能感兴趣的:(Android 用Socket实现PC和手机的文件传输)