Android TCP 檔案客戶端與伺服器DEMO介紹

NO IMAGE
1 Star2 Stars3 Stars4 Stars5 Stars 給文章打分!
Loading...

主要功能是:

1、TCP伺服器提供檔案下載服務,伺服器支援多執行緒。

2、TCP Client從伺服器上下載指定的檔案,Client也支援多執行緒。

首先是伺服器,伺服器是在PC機上,JAVA執行環境,主要參考網上的程式碼,自己做了支援多執行緒處理,程式碼如下:
複製程式碼 程式碼如下:
//file:DownloadServer.java
import java.net.*;
import java.io.*;
class ServerOneDownload extends Thread {
    private Socket socket = null;
    private String downloadRoot = null;
    private static final int Buffer = 8 * 1024;
    public ServerOneDownload(Socket socket, String downloadRoot) {
        super();
        this.socket = socket;
        this.downloadRoot = downloadRoot;
        start();
    }
    // 檢查檔案是否真實存在,核對下載密碼,若檔案不存在或密碼錯誤,則返回-1,否則返回檔案長度
    // 此處只要密碼不為空就認為是正確的
    private long getFileLength(String fileName, String password) {
        // 若檔名或密碼為null,則返回-1
        if ((fileName == null) || (password == null))
            return -1;
        // 若檔名或密碼長度為0,則返回-1
        if ((fileName.length() == 0) || (password.length() == 0))
            return -1;
        String filePath = downloadRoot fileName; // 生成完整檔案路徑
        System.out.println(“DownloadServer getFileLength—–>” filePath);
        File file = new File(filePath);
        // 若檔案不存在,則返回-1
        if (!file.exists())
            return -1;
        return file.length(); // 返回檔案長度
    }
    // 用指定輸出流傳送指定檔案
    private void sendFile(DataOutputStream out, String fileName)
            throws Exception {
        String filePath = downloadRoot fileName; // 生成完整檔案路徑
        // 建立與該檔案關聯的檔案輸入流
        FileInputStream in = new FileInputStream(filePath);
        System.out.println(“DownloadServer sendFile—–>” filePath);
        byte[] buf = new byte[Buffer];
        int len;
        // 反覆讀取該檔案中的內容,直到讀到的長度為-1
        while ((len = in.read(buf)) >= 0) {
            out.write(buf, 0, len); // 將讀到的資料,按讀到的長度寫入輸出流
            out.flush();
        }
        out.close();
        in.close();
    }
    // 提供下載服務
    public void download() throws IOException {
        System.out.println(“啟動下載… “);
        System.out.println(“DownloadServer currentThread—>”
                currentThread().getName());
        System.out.println(“DownloadServer currentThread—>”
                currentThread().getId());
        // 獲取socket的輸入流幷包裝成BufferedReader
        BufferedReader in = new BufferedReader(new InputStreamReader(
                socket.getInputStream()));
        // 獲取socket的輸出流幷包裝成DataOutputStream
        DataOutputStream out = new DataOutputStream(socket.getOutputStream());
        try {
            String parameterString = in.readLine(); // 接收下載請求引數
            // 下載請求引數字串為自定義的格式,由下載檔案相對於下載根目錄的路徑和
            // 下載密碼組成,兩者間以字元 “@ “分隔,此處按 “@ “分割下載請求引數字串
            String[] parameter = parameterString.split(“@ “);
            String fileName = parameter[0]; // 獲取相對檔案路徑
            String password = parameter[1]; // 獲取下載密碼
            // 列印請求下載相關資訊
            System.out.print(socket.getInetAddress().getHostAddress()
                    “提出下載請求, “);
            System.out.println(“請求下載檔案: ” fileName);
            // 檢查檔案是否真實存在,核對下載密碼,獲取檔案長度
            long len = getFileLength(fileName, password);
            System.out.println(“download fileName—–>” fileName);
            System.out.println(“download password—–>” password);
            out.writeLong(len); // 向客戶端返回檔案大小
            out.flush();
            // 若獲取的檔案長度大於等於0,則允許下載,否則拒絕下載
            if (len >= 0) {
                System.out.println(“允許下載 “);
                System.out.println(“正在下載檔案 ” fileName “… “);
                sendFile(out, fileName); // 向客戶端傳送檔案
                System.out.println(fileName “: ” “下載完畢 “);
            } else {
                System.out.println(“下載檔案不存在或密碼錯誤,拒絕下載! “);
            }
        } catch (Exception e) {
            System.out.println(e.toString());
        } finally {
            socket.close(); // 關閉socket
        }
    }
    @Override
    public void run() {
        try {
            download();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // TODO Auto-generated method stub
        super.run();
    }
}
public class DownloadServer {
    private final static int port = 65525;
    private static String root = “C:// “; // 下載根目錄
    public static void main(String[] args) throws IOException {
        String temp = null;
        // 監聽埠
        try {
            // 包裝標準輸入為BufferedReader
            BufferedReader systemIn = new BufferedReader(new InputStreamReader(
                    System.in));
            while (true) {
                System.out.print(“請輸入下載伺服器的下載根目錄: “);
                root = systemIn.readLine().trim(); // 從標準輸入讀取下載根目錄
                File file = new File(root);
                // 若該目錄確實存在且為目錄,則跳出迴圈
                if ((file.exists()) && (file.isDirectory())) {
                    temp = root.substring(root.length() – 1, root.length());
                    if (!temp.equals(“//”))
                        root = “//”;
                }
                break;
            }
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println(“Server start…”);
        try {
            while (true) {
                Socket socket = serverSocket.accept();
                new ServerOneDownload(socket, root);
            }
        } finally {
            serverSocket.close();
        }
    }
}

File Download Client

Client輸入IP和檔名即可直接從伺服器上下載,還是看程式碼。
複製程式碼 程式碼如下:
//file:DownLoadClient.java
package org.piaozhiye.study;
import java.io.IOException;
import java.net.Socket;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class DownLoadClient extends Activity {
    private Button download = null;
    private EditText et_serverIP = null;
    private EditText et_fileName= null;
    private String downloadFile = null;
    private final static int PORT = 65525;
    private final static String defaultIP = “192.168.0.100”;
    private static String serverIP = null;
    private Socket socket;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        download = (Button)findViewById(R.id.download);
        et_serverIP= (EditText)findViewById(R.id.et_serverip);
        et_fileName = (EditText)findViewById(R.id.et_filename);
        et_serverIP.setText(“192.168.0.100”);

      download.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                 serverIP = et_serverIP.getText().toString();
                 if(serverIP == null){
                     serverIP = defaultIP;
                 }
                 System.out.println(“DownLoadClient serverIP—>” serverIP );
                    System.out.println(“DownLoadClient MainThread—>” Thread.currentThread().getId() );

                try{
                    socket = new Socket(serverIP, PORT);

                }catch(IOException e){

                }
                 downloadFile = et_fileName.getText().toString();
            Thread downFileThread = new Thread(new DownFileThread(socket, downloadFile));
            downFileThread.start();
                System.out.println(“DownLoadClient downloadFile—>” downloadFile );
            }
        });

    }
}

file:DownFileThread.java
複製程式碼 程式碼如下:
package org.piaozhiye.study;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
public class DownFileThread extends Thread {
    private Socket socket;
    private String downloadFile;
    private final static int Buffer = 8 * 1024;
    public DownFileThread(Socket socket, String downloadFile) {
        super();
        this.socket = socket;
        this.downloadFile = downloadFile;
    }
    public Socket getSocket() {
        return socket;
    }
    public void setSocket(Socket socket) {
        this.socket = socket;
    }
    public String getDownloadFile() {
        return downloadFile;
    }
    public void setDownloadFile(String downloadFile) {
        this.downloadFile = downloadFile;
    }
    // 向伺服器提出下載請求,返回下載檔案的大小
    private long request(String fileName, String password) throws IOException {
        // 獲取socket的輸入流幷包裝成DataInputStream
        DataInputStream in = new DataInputStream(socket.getInputStream());
        // 獲取socket的輸出流幷包裝成PrintWriter
        PrintWriter out = new PrintWriter(new OutputStreamWriter(
                socket.getOutputStream()));
        // 生成下載請求字串
        String requestString = fileName “@ ” password;
        out.println(requestString); // 發出下載請求
        out.flush();
        return in.readLong(); // 接收並返回下載檔案長度
    }
    // 接收並儲存檔案
    private void receiveFile(String localFile) throws Exception {
        // 獲取socket的輸入流幷包裝成BufferedInputStream
        BufferedInputStream in = new BufferedInputStream(
                socket.getInputStream());
        // 獲取與指定本地檔案關聯的檔案輸出流
        FileOutputStream out = new FileOutputStream(localFile);
        byte[] buf = new byte[Buffer];
        int len;
        // 反覆讀取該檔案中的內容,直到讀到的長度為-1
        while ((len = in.read(buf)) >= 0) {
            out.write(buf, 0, len); // 將讀到的資料,按讀到的長度寫入輸出流
            out.flush();
        }
        out.close();
        in.close();
    }
    // 從伺服器下載檔案
    public void download(String downloadFile) throws Exception {
        try {
            String password = “password”;
            // String downloadFile =”imissyou.mp3″;
            String localpath = “/sdcard/”;
            String localFile = localpath downloadFile;
            long fileLength = request(downloadFile, password);
            // 若獲取的檔案長度大於等於0,說明允許下載,否則說明拒絕下載
            if (fileLength >= 0) {
                System.out.println(“fileLength: ” fileLength ” B”);
                System.out.println(“downing…”);
                receiveFile(localFile); // 從伺服器接收檔案並儲存至本地檔案
                System.out.println(“file:” downloadFile ” had save to “
                        localFile);
            } else {
                System.out.println(“download ” downloadFile ” error! “);
            }
        } catch (IOException e) {
            System.out.println(e.toString());
        } finally {
            socket.close(); // 關閉socket
        }
    }
    @Override
    public void run() {
        System.out.println(“DownFileThread currentThread—>”
                DownFileThread.currentThread().getId());
        // TODO Auto-generated method stub
        try {
            download(downloadFile);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        super.run();
    }

}

layout.xml
複製程式碼 程式碼如下:
<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
    android:orientation=”vertical”
    android:layout_width=”fill_parent”
    android:layout_height=”fill_parent”
    >
<TextView
    android:layout_width=”wrap_content”
    android:layout_height=”wrap_content”
    android:paddingLeft=”10dp”
    android:paddingRight=”10dp”
    android:paddingTop=”5dp”
    android:paddingBottom=”5dp”
    android:text=”伺服器IP:”
    />
    <EditText
    android:id=”@ id/et_serverip”
    android:layout_width=”fill_parent”
    android:layout_height=”wrap_content”
    android:paddingLeft=”10dp”
    android:paddingRight=”10dp”
    android:paddingTop=”5dp”
    android:paddingBottom=”5dp”

    />

    <TextView
    android:layout_width=”wrap_content”
    android:layout_height=”wrap_content”
    android:paddingLeft=”10dp”
    android:paddingRight=”10dp”
    android:paddingTop=”5dp”
    android:paddingBottom=”5dp”
    android:text=”下載檔名:”
    />
    <EditText
    android:id=”@ id/et_filename”
    android:layout_width=”fill_parent”
    android:layout_height=”wrap_content”
    android:paddingLeft=”10dp”
    android:paddingRight=”10dp”
    android:paddingTop=”5dp”
    android:paddingBottom=”5dp”

    />
    <Button
    android:id=”@ id/download”
    android:layout_width=”fill_parent”
    android:layout_height=”wrap_content”
    android:text=”download”
    />
</LinearLayout>

同時別忘了許可權:

<uses-permission android:name=”android.permission.INTERNET” />

您可能感興趣的文章:

Android中實現TCP和UDP傳輸例項Android實現TCP客戶端接收資料的方法Android程式設計實現TCP客戶端的方法Android程式設計實現TCP、UDP客戶端通訊功能示例Android端TCP長連線的效能優化教程分享

相關文章

Android 開發 最新文章