Android TCP 文件客户端与服务器DEMO介绍

Android TCP 文件客户端与服务器DEMO介绍,第1张

概述主要功能是:1、TCP服务器提供文件下载服务,服务器支持多线程。2、TCPClient从服务器上下载指定的文件,Client也支持多线程。

@H_301_1@主要功能是:

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,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,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>

@H_301_1@同时别忘了权限:

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

总结

以上是内存溢出为你收集整理的Android TCP 文件客户端与服务器DEMO介绍全部内容,希望文章能够帮你解决Android TCP 文件客户端与服务器DEMO介绍所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1142483.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-31
下一篇 2022-05-31

发表评论

登录后才能评论

评论列表(0条)

保存