Java:利用TCP编程进行文件下载

来源:互联网 发布:知乎 张佳玮 旅行 编辑:程序博客网 时间:2024/06/05 18:24

package fileDowendd;


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

import java.io.FileOutputStream;

import java.io.DataOutputStream;

import java.net.UnknownHostException;
//文件下载

public class ServerFile {
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(8888);
while(true){
Socket s = ss.accept();
System.out.println(s.getInetAddress()+" "+s.getPort());
new Thread(new Download(s)).start();
}
} catch (IOException e) {
e.printStackTrace();
}

}

}

public class Download implements Runnable {
private Socket s;


public Download(Socket s) {
this.s = s;
}


public void run() {
try {
File f = new File("D:/1.mp4");
long length = f.length();
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeLong(length);
FileInputStream fis = new FileInputStream(f);
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) {
e.printStackTrace();
}
}
}


public class ClientFile {
public static void main(String[] args) {
try {
Socket s=new Socket("192.168.125.119",8888);
DataInputStream dis=new DataInputStream(s.getInputStream());
long length=dis.readLong();
File f=new File("D:/d2.pdf");
FileOutputStream fos=new FileOutputStream(f);
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) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

0 0
原创粉丝点击