SoFunction
Updated on 2025-04-09

Introduction to Android TCP file client and server DEMO

The main functions are:

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

2. TCP Client downloads the specified file from the server, and the Client also supports multi-threading.

First of all, the server is on a PC and JAVA running environment. It mainly refers to the code on the Internet. It supports multi-threading. The code is as follows:

Copy the codeThe code is as follows:

//file:
import .*;
import .*;
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();
        = socket;
        = downloadRoot;
        start();
    }
// Check whether the file really exists and check the download password. If the file does not exist or the password is incorrect, return -1, otherwise return the file length
// As long as the password is not empty, it is considered correct
    private long getFileLength(String fileName, String password) {
// If the file name or password is null, return -1
        if ((fileName == null) || (password == null))
            return -1;
// If the file name or password length is 0, return -1
        if ((() == 0) || (() == 0))
            return -1;
String filePath = downloadRoot + fileName; // Generate the complete file path
        ("DownloadServer getFileLength----->" + filePath);
        File file = new File(filePath);
// If the file does not exist, return -1
        if (!())
            return -1;
return (); // Return file length
    }
// Send the specified file with the specified output stream
    private void sendFile(DataOutputStream out, String fileName)
            throws Exception {
String filePath = downloadRoot + fileName; // Generate the complete file path
// Create a file input stream associated with this file
        FileInputStream in = new FileInputStream(filePath);
        ("DownloadServer sendFile----->" + filePath);
        byte[] buf = new byte[Buffer];
        int len;
//Repeat the contents in the file repeatedly until the length is -1
        while ((len = (buf)) >= 0) {
(buf, 0, len); // Write the read data to the output stream according to the read length
            ();
        }
        ();
        ();
    }
// Provide download services
    public void download() throws IOException {
("Start download...");
        ("DownloadServer currentThread--->"
                + currentThread().getName());
        ("DownloadServer currentThread--->"
                + currentThread().getId());
// Get the input stream of the socket and wrap it into a BufferedReader
        BufferedReader in = new BufferedReader(new InputStreamReader(
                ()));
// Get the output stream of the socket and wrap it into DataOutputStream
        DataOutputStream out = new DataOutputStream(());
        try {
String parameterString = (); // Receive download request parameters
// The download request parameter string is in a custom format, and the path of the download file relative to the download root directory and
// It consists of download password, separated by the character "@". Here, the download request parameter string is divided by "@"
            String[] parameter = ("@ ");
String fileName = parameter[0]; // Get the relative file path
String password = parameter[1]; // Get the download password
// Print request download related information
            (().getHostAddress()
+ "Submit a download request,");
("Request to download the file: " + fileName);
// Check whether the file is real, check the download password, and obtain the file length
            long len = getFileLength(fileName, password);
            ("download fileName----->" + fileName);
            ("download password----->" + password);
(len); // Return file size to the client
            ();
// If the obtained file length is greater than or equal to 0, download is allowed, otherwise download will be refused.
            if (len >= 0) {
("Download allowed");
("Downloading file " + fileName + "...");
sendFile(out, fileName); // Send file to the client
(fileName +": "+"Downloaded");
            } else {
("The download file does not exist or the password is incorrect, download is refused! ");
            }
        } catch (Exception e) {
            (());
        } finally {
(); // Close socket
        }
    }
    @Override
    public void run() {
        try {
            download();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            ();
        }
        // TODO Auto-generated method stub
        ();
    }
}
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 to port
        try {
// The standard input of the packaging is BufferedReader
            BufferedReader systemIn = new BufferedReader(new InputStreamReader(
                    ));
            while (true) {
("Please enter the download root directory of the download server: ");
root = ().trim(); // Read the download root directory from standard input
                File file = new File(root);
// If the directory does exist and is a directory, the loop will break
                if ((()) && (())) {
                    temp = (() - 1, ());
                    if (!("//"))
                        root += "//";
                }
                break;
            }
        } catch (Exception e) {
            (());
        }
        ServerSocket serverSocket = new ServerSocket(port);
        ("Server start...");
        try {
            while (true) {
                Socket socket = ();
                new ServerOneDownload(socket, root);
            }
        } finally {
            ();
        }
    }
}

File Download Client

Client enters the IP and file name to download it directly from the server, or look at the code.

Copy the codeThe code is as follows:

//file:
package ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
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) {
        (savedInstanceState);
        setContentView();
        download = (Button)findViewById();
        et_serverIP= (EditText)findViewById(.et_serverip);
        et_fileName = (EditText)findViewById(.et_filename);
        et_serverIP.setText("192.168.0.100");

      (new () {

            @Override
            public void onClick(View v) {
                 serverIP = et_serverIP.getText().toString();
                 if(serverIP == null){
                     serverIP = defaultIP;
                 }
                 ("DownLoadClient serverIP--->" + serverIP );
                    ("DownLoadClient MainThread--->" + ().getId() );

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

                }catch(IOException e){

                }
                 downloadFile = et_fileName.getText().toString();
            Thread downFileThread = new Thread(new DownFileThread(socket, downloadFile));
            ();
                ("DownLoadClient downloadFile--->" + downloadFile );
            }
        });

    }
}

file:
Copy the codeThe code is as follows:

package ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
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();
        = socket;
        = downloadFile;
    }
    public Socket getSocket() {
        return socket;
    }
    public void setSocket(Socket socket) {
        = socket;
    }
    public String getDownloadFile() {
        return downloadFile;
    }
    public void setDownloadFile(String downloadFile) {
        = downloadFile;
    }
// Submit a download request to the server and return the size of the downloaded file
    private long request(String fileName, String password) throws IOException {
// Get the socket's input stream and wrap it into DataInputStream
        DataInputStream in = new DataInputStream(());
// Get the output stream of the socket and wrap it into PrintWriter
        PrintWriter out = new PrintWriter(new OutputStreamWriter(
                ()));
// Generate download request string
        String requestString = fileName + "@ " + password;
(requestString); // Issue a download request
        ();
return (); // Receive and return the downloaded file length
    }
// Receive and save files
    private void receiveFile(String localFile) throws Exception {
// Get the socket's input stream and wrap it into a BufferedInputStream
        BufferedInputStream in = new BufferedInputStream(
                ());
// Get the file output stream associated with the specified local file
        FileOutputStream out = new FileOutputStream(localFile);
        byte[] buf = new byte[Buffer];
        int len;
//Repeat the contents in the file repeatedly until the length is -1
        while ((len = (buf)) >= 0) {
(buf, 0, len); // Write the read data to the output stream according to the read length
            ();
        }
        ();
        ();
    }
// 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 obtained file length is greater than or equal to 0, download is allowed, otherwise it means that download is refused.
            if (fileLength >= 0) {
                ("fileLength: " + fileLength + " B");
                ("downing...");
receiveFile(localFile); // Receive file from the server and save it to local file
                ("file:" + downloadFile + " had save to "
                        + localFile);
            } else {
                ("download " + downloadFile + " error! ");
            }
        } catch (IOException e) {
            (());
        } finally {
(); // Close socket
        }
    }
    @Override
    public void run() {
        ("DownFileThread currentThread--->"
                + ().getId());
        // TODO Auto-generated method stub
        try {
            download(downloadFile);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            ();
        }
        ();
    }

}


Copy the codeThe code is as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:andro
    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="Server IP:"
    />
    <EditText
    android:
    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:
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:paddingTop="5dp"
    android:paddingBottom="5dp"

    />
    <Button
    android:
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="download"
    />
</LinearLayout>

Don't forget the permissions:

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