Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android TCP 文件客戶端與服務器DEMO介紹

Android TCP 文件客戶端與服務器DEMO介紹

編輯:關於Android編程

主要功能是:

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" />

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved