您的位置:首页 > 理论基础 > 计算机网络

多线程和网络通信实现的简单文件下载

2014-04-03 15:57 525 查看
package com.qianfeng.tcphomework02;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

public class DownloadFileClient {
public static void main(String[] args) {

Socket s = null;
try {
s = new Socket("127.0.0.1", 9999);
DataInputStream dis = new DataInputStream(s.getInputStream());
long length = dis.readLong();
File file = new File("c:/Sunset.jpg");
int count = 0;
while(file.exists()){
file = new File(s.getInetAddress() + "(" + (++count) + ").jpg");
}
FileOutputStream fos = new FileOutputStream(file);
int sum = 0;//累加
int n = 0;//每次读取的字节数
byte[] b = new byte[1024];
long start = System.currentTimeMillis();
while (sum < length) {
n = dis.read(b);
fos.write(b, 0, n);
sum += n;
}
long end = System.currentTimeMillis();
System.out.println("文件大小:"+length);
System.out.println("下载字节数:"+sum);
System.out.println("花费时间:"+(end-start)+"ms");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

}
package com.qianfeng.tcphomework02;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class DownloadFileServer {

public static void main(String[] args) {
// TODO Auto-generated method stub
ServerSocket ss = null;
try {
ss = new ServerSocket(9999);

while(true){
Socket s = ss.accept();
new Thread(new DownloadTask(s)).start();
}

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {

ss.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

}

package com.qianfeng.tcphomework02;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;

public class DownloadTask implements Runnable {

private Socket s;

public DownloadTask(Socket s) {
super();
this.s = s;
}

@Override
public void run() {
// TODO Auto-generated method stub
File file = new File("c:/Sunset.jpg");
long length = file.length();

DataOutputStream dos;
try {
dos = new DataOutputStream(s.getOutputStream());
dos.writeLong(length);

FileInputStream fis = new FileInputStream(file);
byte[] b = new byte[1024];
int n = 0;
while ((n = fis.read(b)) != -1) {
dos.write(b, 0, n);
}
System.out.println("下载完毕!");

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: