2021.6.19笔记 综合案例:文件上传

原理

在这里插入图片描述


客户端代码

在这里插入图片描述

public class PracticeClient {
    public static void main(String[] args) throws IOException {
        FileInputStream fips = new FileInputStream("H:\\test\\aa.txt");
        Socket so = new Socket("175.0.0.1",8888);
        OutputStream ops = so.getOutputStream();
        byte[] bytes = new byte[1024];
        int len = 0;
        while((len = fips.read(bytes)) != -1) {
            ops.write(bytes,0,len);
        }
        InputStream ips = so.getInputStream();
        while((len = ips.read(bytes)) != -1) {
            System.out.println(new String(bytes,0,len));
        }
        fips.close();
        so.close();
    }
}

服务器代码

在这里插入图片描述

public class PracticeServer {
    public static void main(String[] args) throws IOException {
        ServerSocket sso = new ServerSocket(8888);
        Socket socket = sso.accept();
        InputStream ips = socket.getInputStream();
        File file = new File("H:\\test\\bba");
        if(!file.exists()) {
            file.mkdirs();
        }
        FileOutputStream fops = new FileOutputStream(file + "\\server.txt");
        byte[] bytes = new byte[1024];
        int len = 0;
        while((len = ips.read(bytes)) != -1) {
            fops.write(bytes,0,len);
        }
        OutputStream ops = socket.getOutputStream();
        ops.write("收到谢谢".getBytes());
        fops.close();
        socket.close();
        sso.close();
    }
}

阻塞问题

在这里插入图片描述

利用socket.shutdownOutput即可解决问题

public class PracticeClient {
    public static void main(String[] args) throws IOException {
        FileInputStream fips = new FileInputStream("F:\\test\\aa.txt");
        Socket so = new Socket("192.168.2.178",8888);
        OutputStream ops = so.getOutputStream();
        byte[] bytes = new byte[1024];
        int len = 0;
        while((len = fips.read(bytes)) != -1) {
            ops.write(bytes,0,len);
        }
        so.shutdownOutput();
        InputStream ips = so.getInputStream();
        while((len = ips.read(bytes)) != -1) {
            System.out.println(new String(bytes,0,len));
        }
        fips.close();
        so.close();
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值