android连接socket服务器上传下载多个文件
1.socket服务端SocketServer.java

public class SocketServer {
int port = ;// 端口号,必须与客户端一致
// 选择进行传输的文件(测试)
String path = "C:\\Temp";
String filePath = "E:\\img.png";
Socket client;
public static void main(String arg[]) {
System.out.println("-----准备建立socket链接----");
new SocketServer().start();
}
void start() {
try {
ServerSocket serverSocket = new ServerSocket(port);
while (true) {
// IOException侦听并接受到此套接字的连接。此方法在进行连接之前一直阻塞。
client = serverSocket.accept();
try {
System.out.println("-----建立socket链接----");
// 向客户端发送多个文件(测试)
setMoreMessage(path);
} catch (Exception e) {
e.printStackTrace();
} finally {
client.close();
System.out.println("close");
}
}
} catch (Exception e) {
e.printStackTrace();
}
} // 向客户端发送信息
private void setMessage(String filePath, DataOutputStream ps)
throws IOException {
File fi = new File(filePath);
System.out.println("要发送的文件长度:" + (int) fi.length() + "字節");
// 向客户端发送信息
DataInputStream fis = new DataInputStream(new BufferedInputStream(
new FileInputStream(filePath)));
// 将文件名及长度传给客户端。中文名需要处理
ps.writeUTF(fi.getName());
ps.flush();
ps.writeLong((long) fi.length());
ps.flush(); int bufferSize = ;
byte[] buf = new byte[bufferSize]; while (true) {
int read = ;
if (fis != null) {
read = fis.read(buf);
} if (read == -) {
break;
}
ps.write(buf, , read);
}
ps.flush();
fis.close();
System.out.println("文件中传输。。。");
} /**
* 向客户端发送多个文件
* @param path
* @throws IOException
*/
private void setMoreMessage(String path) throws IOException {
File root = new File(path);
if (!root.exists()) {
root.mkdir();
return;
}
String[] colum = root.list();
System.out.println("The file's num is :" + colum.length);
// 写入流
DataOutputStream ps = new DataOutputStream(client.getOutputStream());
// 写出流
DataInputStream dis = new DataInputStream(new BufferedInputStream(
client.getInputStream()));
// 写出文件总个数
ps.writeInt(colum.length);
ps.flush(); System.out.println(dis.readBoolean() ? "开始上传文件" : "开始上传失败");// 接收客户端返回的上传信息
System.out.println();
for (int i = ; i < colum.length; i++) {
System.out.println("The colum's content is :" + colum[i]);
String filePath = path + "\\" + colum[i];
setMessage(filePath, ps);// 上传文件
System.out.println(dis.readBoolean() ? "成功上传文件" : "上传失败");// 接收客户端返回的上传信息
}
System.out.println("-----文件传输完成------");
} // 接收客户端发送的信息
private void getMessage(DataInputStream inputStream) {
try {
// 本地保存路径,文件名会自动从服务器端继承而来。
String savePath = "D://android_img/";
File file = new File(savePath);
// 创建文件夹
if (!file.exists()) {
file.mkdirs();
}
int bufferSize = ;
byte[] buf = new byte[bufferSize];
int passedlen = ;
long len = ; savePath += inputStream.readUTF();
DataOutputStream fileOut = new DataOutputStream(
new BufferedOutputStream(new BufferedOutputStream(
new FileOutputStream(savePath))));
len = inputStream.readLong(); System.out.println("文件的长度为:" + len + "\n");
System.out.println("开始接收文件!" + "\n" + getTime()); while (true) {
int read = ;
if (inputStream != null) {
read = inputStream.read(buf);
}
passedlen += read;
if (read == -) {
break;
}
// 进度条,如果是大文件,可能会重复打印出一些相同的百分比
System.out.println("文件接收了" + (passedlen * / len) + "%\n");
fileOut.write(buf, , read);
}
// 花费的时间
System.out.println("接收完成,文件存为" + savePath + "\n" + getTime()); fileOut.close();
} catch (Exception e) {
System.out.println("接收消息错误" + "\n" + e.toString());
return;
}
}
public static String getTime() {
long tmp = System.currentTimeMillis();// 花费的时间
SimpleDateFormat formatter = new SimpleDateFormat(
"yyyy年-MM月dd日-HH时mm分ss秒");
Date date = new Date(tmp);
return formatter.format(date);
}
}

2.android客户端下文件ImageDownLoadUtil.java

/**
* 发送接收文件
* @ClassName: ClientTest
* @Description: TODO
* @author jalin
* @date 2014-4-16 上午11:37:30
*/
public class ImageDownLoadUtil extends Thread implements Runnable {
private ClientSocket client = null;
private Context context;
private String IP = "192.168.1.2";// 本地ip
private int PORT = ; // 端口号
private boolean resule = false;
String filePath = "";// android手机文件路径
String filename = "";//存放圖片的文件夾名
public int type = ;//模式
public boolean isContinue = true; public ImageDownLoadUtil(Context context) {
this.context = context;
this.filePath = Session.DATABASE_PATH;
filename=Session.IMAGE_FILENAME;
try {
if (createConnection()) {
// type = 2;//接受文件
// sendMessage();//发送文件、信息
type = ;//接受文件
this.start();
}
} catch (Exception ex) {
ex.printStackTrace();
}
} /**
* 得到socket鏈接通道
* @return
*/
private boolean createConnection() {
client = new ClientSocket(IP, PORT);
try {
client.CreateConnection();
System.out.print("创建连接成功!");
return true;
} catch (Exception e) {
System.out.print("创建连接失败!");
return false;
}
}
@Override
public void run() {
switch (type) {
case :// 下载多個图片文件
resule = false;
if (client == null)
return;
DataInputStream inputStream = null;// 写入流
DataOutputStream out = null;// 写出流
try {
inputStream = client.getDataInputStream();// 写入流
out = client.getDataOutputStream();// 写出流 int fileLenght = inputStream.readInt();//得到文件總數量 out.writeBoolean(true);// 发送上传開始標誌
out.flush();
// 文件存储路径
String savePath = filePath + "/" + filename + "/";
while ((fileLenght--) > ) {
resule=saveFile(inputStream,savePath);// 保存图片
out.writeBoolean(resule);// 发送上传结果
out.flush();
}
} catch (Exception e) {
System.out.print("接收文件出错!");
return;
}finally{
Message msg=new Message();
if (resule) {
msg.what=;
}else{
msg.what=-;
}
handler.sendMessage(msg);
}
break; default:
break;
}
} /**
* 保存文件
* @param inputStream
* @return
*/
private boolean saveFile(DataInputStream inputStream,String savePath) {
boolean resule=false;
try {
if (!new File(savePath).exists()) {
new File(savePath).mkdir();
}
int bufferSize = * ;
byte[] buf = new byte[bufferSize];
int passedlen = ;
long len = ;
//得到文件名称
String saveFilePate=savePath +inputStream.readUTF();
File image = new File(saveFilePate);
if (image.exists()) {
image.delete();
}
DataOutputStream fileOut = new DataOutputStream(
new BufferedOutputStream(new BufferedOutputStream(
new FileOutputStream(saveFilePate))));
len = inputStream.readLong(); System.out.println("文件长度:" + len);
long tmp = System.currentTimeMillis();// 获取当前系统时间
System.out.println("开始发送时间:" + "\n" + tmp);
int redLen = ;
while (true) {
int read = ;
if (inputStream != null && passedlen < len) {//文件接收结束标志
read = inputStream.read(buf);
}
passedlen += read;
if (read == - || read == ) {
break;
}
//
System.out.println("当前进度:" + (passedlen * / len) + "%\n");
fileOut.write(buf, , read);
}
tmp = System.currentTimeMillis();// 当前时间
System.out.println("文件保存路径:" + saveFilePate + "---时间:" + tmp);
fileOut.close();
resule = true;
} catch (Exception e) {
System.out.println("出错了:" + e.toString());
return resule;
}finally{
}
return resule;
} /*
* 发送文件、信息
*/
private void sendMessage() {
if (client == null)
return;
try {
System.out.print("文件路径:" + filePath);
client.sendMessage(filePath);
} catch (Exception e) {
System.out.print("发送文件出错!");
}
}
Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case :
// 执行定时器时间到了之后由handler传递的任务
Toast.makeText(context, "下载图片成功", Toast.LENGTH_LONG).show();
break;
case -:
// 执行定时器时间到了之后由handler传递的任务
Toast.makeText(context, "下载图片失败", Toast.LENGTH_LONG).show();
break;
}
super.handleMessage(msg);
}
};
}

3.Socket客戶端

/**
* Socket客戶端
*
* @ClassName: ClientSocket
* @Description: TODO
* @author jalin
* @date 2014-4-16 下午5:10:31
*/
public class ClientSocket {
private String ip; private int port; private Socket socket = null; private DataOutputStream out = null; private DataInputStream getMessageStream = null; public ClientSocket(String ip, int port) {
this.ip = ip;
this.port = port;
}
/**
* 创建socket连接
*
* @throws Exception
* exception
*/
public void CreateConnection() throws Exception {
try {
socket = new Socket(ip, port);
} catch (Exception e) {
e.printStackTrace();
if (socket != null)
socket.close();
throw e;
} finally {
}
}
/**
* 發送圖片
* @param filePath
* @throws Exception
*/
public void sendMessage(String filePath) throws Exception {
try {
// 获取本地文件
File file = new File(filePath);
getMessageStream = new DataInputStream(new BufferedInputStream(
new FileInputStream(filePath)));
out = new DataOutputStream(socket.getOutputStream());
out.writeUTF(filePath);
// 发送文件属性
out.writeUTF(file.getName());
out.flush();
out.writeLong((long) file.length());
out.flush();
int bufferSize = * ;
byte[] buf = new byte[bufferSize];
while (true) {
int read = ;
if (getMessageStream != null) {
read = getMessageStream.read(buf);
} if (read == -) {
break;
}
out.write(buf, , read);
}
out.flush();
getMessageStream.close();
System.out.println("-----发送完成------");
} catch (Exception e) {
System.out.println(e.toString());
} finally {
if (out != null)
out.close();
}
} public DataOutputStream getDataOutputStream() {
try {
out = new DataOutputStream(socket.getOutputStream());
return out;
} catch (IOException e) {
e.printStackTrace();
try {
if (out != null) {
out.close();
}
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
return null;
} public DataInputStream getDataInputStream() throws Exception {
try {
getMessageStream = new DataInputStream(new BufferedInputStream(
socket.getInputStream()));
return getMessageStream;
} catch (Exception e) {
e.printStackTrace();
if (getMessageStream != null)
getMessageStream.close();
throw e;
} finally {
}
} public int getFileLenght() {
try {
return getDataInputStream().readInt();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return -;
}
public void shutDownConnection() {
try {
if (out != null)
out.close();
if (getMessageStream != null)
getMessageStream.close();
if (socket != null)
socket.close();
} catch (Exception e) { }
}
}

4.activity按钮事件 new ImageDownLoadUtil(this);

Android连接socket服务器上传下载多个文件的更多相关文章

  1. 向linux服务器上传下载文件方式收集

    向linux服务器上传下载文件方式收集 1. scp [优点]简单方便,安全可靠:支持限速参数[缺点]不支持排除目录[用法] scp就是secure copy,是用来进行远程文件拷贝的.数据传输使用 ...

  2. Linux下不借助工具实现远程linux服务器上传下载文件

    # Linux下不借助工具实现远程linux服务器上传下载文件 ## 简介 - Linux下自带ssh工具,可以实现远程Linux服务器的功能- Linux下自带scp工具,可以实现文件传输功能 ## ...

  3. Python 一键上传下载&一键提交文件到SVN入基线工具

    一键上传下载&一键提交文件到SVN入基线工具   by:授客 QQ:1033553122 实现功能 1 测试环境 1 使用说明 1   注: 根据我司项目规则订制的一套工具,集成以下功能,源码 ...

  4. 【转】Android 服务器之SFTP服务器上传下载功能

    原文网址:http://blog.csdn.net/tanghua0809/article/details/47056327 本文主要是讲解Android服务器之SFTP服务器的上传下载功能,也是对之 ...

  5. 【转】Android 服务器之SFTP服务器上传下载功能 -- 不错

    原文网址:http://blog.csdn.net/tanghua0809/article/details/47056327 本文主要是讲解Android服务器之SFTP服务器的上传下载功能,也是对之 ...

  6. SFTP远程连接服务器上传下载文件-qt4.8.0-vs2010编译器-项目实例

    本项目仅测试远程连接服务器,支持上传,下载文件,更多功能开发请看API自行开发. 环境:win7系统,Qt4.8.0版本,vs2010编译器 qt4.8.0-vs2010编译器项目实例下载地址:CSD ...

  7. Android+Spring Boot 选择+上传+下载文件

    2021.02.03更新 1 概述 前端Android,上传与下载文件,使用OkHttp处理请求,后端使用Spring Boot,处理Android发送来的上传与下载请求.这个其实不难,就是特别多奇奇 ...

  8. java 通过sftp服务器上传下载删除文件

    最近做了一个sftp服务器文件下载的功能,mark一下: 首先是一个SftpClientUtil 类,封装了对sftp服务器文件上传.下载.删除的方法 import java.io.File; imp ...

  9. Spring学习---Spring中利用组件实现从FTP服务器上传/下载文件

    FtpUtil.java import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundExcepti ...

随机推荐

  1. placement new和delete

    注意,我们无法改变new和delete操作符. 但是我们可以重载来里面的operator new 和 operator delete 方法,这个方法是被new操作符调用的,调用之后获得地址,会继续用构 ...

  2. 第6章8节《MonkeyRunner源代码剖析》Monkey原理分析-事件源-事件源概览-小结

    本章我们重点环绕处理网络过来的命令的MonkeySourceNetwork这个事件源来阐述学习Monkey是怎样处理MonkeyRunner过来的命令的.以下总结下MonkeyRunner从启动Mon ...

  3. Android中System.currentTimeMillis()

    函数: System.currentTimeMillis(): 功能:产生一个当前的毫秒,这个毫秒事实上就是自1970年1月1日0时起的毫秒数,Date()事实上就是相当于Date(System.cu ...

  4. Entity Framework之Model First开发方式

    一.Model First开发方式 在项目一开始,就没用数据库时,可以借助EF设计模型,然后根据模型同步完成数据库中表的创建,这就是Model First开发方式.总结一点就是,现有模型再有表. 二. ...

  5. POJ 1330 Nearest Common Ancestors 倍增算法的LCA

    POJ 1330 Nearest Common Ancestors 题意:最近公共祖先的裸题 思路:LCA和ST我们已经很熟悉了,但是这里的f[i][j]却有相似却又不同的含义.f[i][j]表示i节 ...

  6. Design Pattern - Service Locator Pattern--转载

    原文地址:http://www.tutorialspoint.com/design_pattern/service_locator_pattern.htm The service locator de ...

  7. 线性同余同余方程组解法(excrt)

    [问题描述] 求关于 x 的同余方程组 x%a 1 =b 1  a1=b1 x%a 2 =b 2  a2=b2 x%a 3 =b 3  a3=b3 x%a 4 =b 4  a4=b4 的大于等于 0 ...

  8. SVN仓库目录结构

    SVN仓库目录结构Repository: trunktagsbranches trunk(主干|主线) branchs(分支) tags(标记) truck(主干|主线|主分支):是用来做主方向开发的 ...

  9. codeforces111D. Petya and Coloring(组合数学,计数问题)

    传送门: 解题思路: 要求一条直线分割矩阵时左右颜色数一样,那么就说明一个问题.直线左右移动时是不会改变左右矩阵的颜色集合的.所以说明:2~m-1列的颜色集一定属于第一列与第m列颜色集的交集.而且第一 ...

  10. U-BOOT启动流程分析--start_armboot函数(二)

    第二阶段的功能: 初始化本阶段所需的硬件设备(主要设置系统时钟.初始化串口.Flash.网卡.USB) 检测系统内存映射(memory map) 将内核映像和根文件系统映象从Flash上读到RAM空间 ...