从服务端传输文件到客户端(一对一)

public class FTPServer {

//服务器
	public void start(File target) throws IOException{
		//创建一个服务器
		ServerSocket ss = new ServerSocket(5678);
		//开始监听
		Socket  s = ss.accept();
		//获取基于socket的输出流
		PrintStream ps = new PrintStream(s.getOutputStream());
		//获取目标文件的输入流
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(target));
		System.out.println("开始传输...");
		byte[] b = new byte[1024];
		int len = 0;
		while((len = bis.read(b)) != -1){
			ps.write(b, 0, len);
		}
		System.out.println("传输完成!");
		bis.close();
		ps.close();
		ss.close();
	}
	
	public static void main(String[] args) throws IOException {
	
		File target = new File("D:\\素材\\视频\\video.mp4");
		new FTPServer().start(target);
	}

}
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

public class FTPClient {
//客户端
	public static void main(String[] args) throws UnknownHostException, IOException {
		
		File f = new File("C:\\Users\\mrchai\\Desktop\\video.mp4");
		
		Socket s = new Socket("192.168.4.254",5678);
		//获取目标文件的输出流
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(f));
		//获取socket的输入流
		BufferedInputStream bis = new BufferedInputStream(s.getInputStream());
		byte[] b = new byte[1024];
		int len = 0;
		while((len = bis.read(b)) != -1){
			bos.write(b, 0, len);
		}
		bis.close();
		bos.close();
		s.close();
	}
}

 

你可能感兴趣的:(从服务端传输文件到客户端(一对一))