网络编程,运用TCP/IP协议,实现文件的下载

创建服务端:
public class FileServer02 extends Thread{
	
	private File source;
	private Socket s;
	
	public FileServer02(File source, Socket s) {
		super();
		this.source = source;
		this.s = s;
	}

	@Override 
	public void run() {
		try {
			System.out.println("向" + s.getInetAddress().getHostAddress() + "传输……");
			// 获取源文件的输入流
			InputStream in = new FileInputStream(source);
			// 获取socket的输出流
			OutputStream out = s.getOutputStream();
			// 传输
			TransferUtils.transfer(in, out);
			System.out.println(s.getInetAddress().getHostAddress() + "传输完成");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (s != null)
					s.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args) throws IOException {
		
		// 准备需要传输的文件对象
		File target = new File("");
		//在指定端口创建服务
		ServerSocket server = new ServerSocket(6666);
		
		while(true) {
			Socket s = server.accept();
			//创建文件传输的线程并启动
			new FileServer02(target,s).start();
		}
	}

}
创建客户端:
public class FileClient {
	
	public static void main(String[] args) throws UnknownHostException, IOException {
		
		File f = new File("D:\\测试\\第二级目录2\\a.mp4");
		
		try(
			//连接知道ip指定端口服务
			Socket s = new Socket("192.168.7.141",6666);
			//获取基于Socket的输入流并包装为缓冲流
			BufferedInputStream bis = new BufferedInputStream(s.getInputStream());
			BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(f));
		){
			System.out.println("开始接收……");
			int b = 0;
			while ((b = bis.read()) != -1) {
				bos.write(b);
			}
			System.out.println("接收完成完成");
		}catch (Exception e) {
			e.printStackTrace();
		}
	}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值