Introduction to Android TCP file client and server DEMO

  • 2020-05-19 05:47:13
  • OfStack

The main functions are:

1. TCP server provides file download service, and the server supports multi-threading.

2. TCP Client downloads the specified files from the server. Client also supports multithreading.

The first is the server. The server is on the PC machine. JAVA runs in the environment.


//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();
    }
    //  Check whether the file is real, check the download password, if the file does not exist or the password is wrong, then return -1 , otherwise return the file length 
    //  This is considered correct as long as the password is not empty 
    private long getFileLength(String fileName, String password) {
        //  If the file name or password is null , the return -1
        if ((fileName == null) || (password == null))
            return -1;
        //  If the filename or password length is 0 , the return -1
        if ((fileName.length() == 0) || (password.length() == 0))
            return -1;
        String filePath = downloadRoot + fileName; //  Generate the full file path 
        System.out.println("DownloadServer getFileLength----->" + filePath);
        File file = new File(filePath);
        //  Returns if the file does not exist -1
        if (!file.exists())
            return -1;
        return file.length(); //  Return file length 
    }
    //  Sends the specified file with the specified output stream 
    private void sendFile(DataOutputStream out, String fileName)
            throws Exception {
        String filePath = downloadRoot + fileName; //  Generate the full file path 
        //  Create the file input stream associated with the file 
        FileInputStream in = new FileInputStream(filePath);
        System.out.println("DownloadServer sendFile----->" + filePath);
        byte[] buf = new byte[Buffer];
        int len;
        //  The contents of this file are read repeatedly until the length is -1
        while ((len = in.read(buf)) >= 0) {
            out.write(buf, 0, len); //  The read data is written to the output stream as long as it is read 
            out.flush();
        }
        out.close();
        in.close();
    }
    //  Download service 
    public void download() throws IOException {
        System.out.println(" Start the download ... ");
        System.out.println("DownloadServer currentThread--->"
                + currentThread().getName());
        System.out.println("DownloadServer currentThread--->"
                + currentThread().getId());
        //  To obtain socket The input stream and wrapped into BufferedReader
        BufferedReader in = new BufferedReader(new InputStreamReader(
                socket.getInputStream()));
        //  To obtain socket The output stream is wrapped into DataOutputStream
        DataOutputStream out = new DataOutputStream(socket.getOutputStream());
        try {
            String parameterString = in.readLine(); //  Receive download request parameters 
            //  Download the request parameter string for the custom format, by downloading the file relative to the download root directory and 
            //  Download password composition, with characters between the two  "@ " To separate, click here  "@ " Split the download request parameter string 
            String[] parameter = parameterString.split("@ ");
            String fileName = parameter[0]; //  Gets the relative file path 
            String password = parameter[1]; //  Get the download password 
            //  Print the request to download the information 
            System.out.print(socket.getInetAddress().getHostAddress()
                    + " Make a download request,  ");
            System.out.println(" Request file download : " + fileName);
            //  Check if the file is real, check the download password, and get the length of the file 
            long len = getFileLength(fileName, password);
            System.out.println("download fileName----->" + fileName);
            System.out.println("download password----->" + password);
            out.writeLong(len); //  Returns the file size to the client 
            out.flush();
            //  If the length of the retrieved file is greater than or equal to 0, Allow the download, otherwise refuse to download 
            if (len >= 0) {
                System.out.println(" Allowed to download  ");
                System.out.println(" Downloading file  " + fileName + "... ");
                sendFile(out, fileName); //  Send the file to the client 
                System.out.println(fileName +": "+" The download  ");
            } else {
                System.out.println(" Download file does not exist or password error, refuse to download!  ");
            }
        } catch (Exception e) {
            System.out.println(e.toString());
        } finally {
            socket.close(); //  Shut down 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:// "; //  Download the root directory 
    public static void main(String[] args) throws IOException {
        String temp = null;
        //  Listen on port 
        try {
            //  Packing standard input is BufferedReader
            BufferedReader systemIn = new BufferedReader(new InputStreamReader(
                    System.in));
            while (true) {
                System.out.print(" Please enter the download root directory of the download server:  ");
                root = systemIn.readLine().trim(); //  Read the download root from standard input 
                File file = new File(root);
                //  If the directory does exist and is a directory, break out of the loop 
                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 enters IP and file name to download it directly from the server, or to see the code.


//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;
    }
    //  Make a download request to the server and return the size of the downloaded file 
    private long request(String fileName, String password) throws IOException {
        //  To obtain socket The input stream and wrapped into DataInputStream
        DataInputStream in = new DataInputStream(socket.getInputStream());
        //  To obtain socket The output stream is wrapped into PrintWriter
        PrintWriter out = new PrintWriter(new OutputStreamWriter(
                socket.getOutputStream()));
        //  Generate the download request string 
        String requestString = fileName + "@ " + password;
        out.println(requestString); //  Make a download request 
        out.flush();
        return in.readLong(); //  Receive and return the download file length 
    }
    //  Receive and save the file 
    private void receiveFile(String localFile) throws Exception {
        //  To obtain socket The input stream and wrapped into BufferedInputStream
        BufferedInputStream in = new BufferedInputStream(
                socket.getInputStream());
        //  Gets the file output stream associated with the specified local file 
        FileOutputStream out = new FileOutputStream(localFile);
        byte[] buf = new byte[Buffer];
        int len;
        //  The contents of this file are read repeatedly until the length is -1
        while ((len = in.read(buf)) >= 0) {
            out.write(buf, 0, len); //  The read data is written to the output stream as long as it is read 
            out.flush();
        }
        out.close();
        in.close();
    }
    //  Download the file from the server 
    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);
            //  If the length of the retrieved file is greater than or equal to 0 , indicating that download is allowed, otherwise, indicating that download is refused 
            if (fileLength >= 0) {
                System.out.println("fileLength: " + fileLength + " B");
                System.out.println("downing...");
                receiveFile(localFile); //  Receive the file from the server and save it to a local file 
                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(); //  Shut down 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=" The server 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=" Download file name :"
    />
    <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>

And don't forget permissions:

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


Related articles: