java之TCP上传文件到服务器

客户端代码:

public class TCP_upload {
	
	static String path = "C://Users/小苏/Downloads/1046025.lrc";
	
	
	public static void main(String[] args) {
		Socket s = null;
		FileInputStream fis = null;
		try {
			//1.创建Socket并绑定服务端监听端口
			s = new Socket("localhost", 10001);
			
			fis = new FileInputStream(path);
			
			OutputStream os = s.getOutputStream();
			
			byte[] buff = new byte[1024];
			
			int len;
			while((len = fis.read(buff)) != -1){
				os.write(buff, 0, len);
			}
			//结束标记
			s.shutdownOutput();
			
			//接收服务端返回的信息
			BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
			System.out.println(reader.readLine());
			
			
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(s != null){
				try {
					//4.关闭资源
					s.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(fis != null){
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
服务端代码:

class TCPServer_upload{
	static String path1 = "C://Users/小苏/Downloads/(复件)1046025.lrc";
	public static void main(String[] args){
		FileOutputStream fos = null;
		try {
			//1.创建服务端并绑定监听端口
			ServerSocket ss = new ServerSocket(10001);
			//2.接收客户端数据,是阻塞方法
			Socket s = ss.accept();
			System.out.println(s.getInetAddress().getHostAddress());
			//3.得到输入流,用客户端的输入流读客户端发送过来的数据
			InputStream is = s.getInputStream();
			byte[] buff = new byte[1024];
			int len ;
			
			fos = new FileOutputStream(path1);
			
			while((len = is.read(buff)) != -1){
				fos.write(buff, 0, len);
			}
			//通知客户端
			OutputStream os = s.getOutputStream();
			byte[] b = "复制完成".getBytes();
			os.write(b );
			
			s.close();
			ss.close();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(fos != null){
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值