tcp Socket 实现文件传输

使用 Socket 完成
文件输入 —服务端—输出—客户端—输出—新文件地址

服务端

public class ServerDemo {

	public static void main(String[] args) {
		// TODO 服务器端
		int count = 0;
		ServerSocket socket=null;
		try {
			socket = new ServerSocket(8877);
			FileInputStream fileInputStream = new FileInputStream("D:\\1906\\JAVA1906\\day36\\kk.jpg");
			while (true) {
				if (count >= 1) {
					break;
				}
				Socket accept = socket.accept();
				System.out.println("=========客户端===" + socket.getInetAddress() + "===已接入");
				// 获取客户端的输入输出流
				OutputStream outputStream = accept.getOutputStream();
				byte[] buf = new byte[1024];
				int len=0;
				while ((len=fileInputStream.read(buf))!=-1) {
					outputStream.write(buf,0,len);
					outputStream.flush();
				}
				outputStream.write("okokokokoko".getBytes());
				outputStream.flush();
				System.out.println("=========文件已传输成功===等待客户端接收====");
				count++;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				Thread.sleep(3000);
				socket.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}

客户端

public class CilentDemo {

	public static void main(String[] args) {
		// TODO 客户端1----想下载一张图片
		Socket socket = null;
		try {
			socket = new Socket(InetAddress.getLocalHost(), 8877);
			FileOutputStream fileOutputStream = new FileOutputStream("D:\\1906\\JAVA1906\\day36\\qwe.jpg");
			// 使用socket来获取输入输出流
			InputStream inputStream = socket.getInputStream();
			byte[] buf = new byte[1024];
			int len = 0;
			String huaString = "";
			while ((len = inputStream.read(buf)) != -1) {
				fileOutputStream.write(buf, 0, len);
				fileOutputStream.flush();
				huaString = new String(buf, 0, len);
				if (huaString.contains("okokokokoko")) {
					break;
				}
			}
			System.out.println("=========客户端=====");
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			if (socket!=null) {
				try {
					socket.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值