文件上传(Socket)

本文介绍了如何通过Socket在客户端和服务器端实现文件上传的过程。客户端部分讲解了上传的步骤,服务器端则阐述了接收文件的流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

文件上传的客户端:

    1.创建客户端,连接服务端
    2.创建文件输入流
    3.获取Socket输出流
    4.读取文件数据
    5.写入到Socket输出流
    6.循环读写
public class UploadClient {
    public static void main(String[] args) throws IOException {
        System.out.println("客户端启动了");
        //1.创建客户端,连接服务器
        Socket socket = new Socket("127.0.0.1",10086);

        //2.创建文件输入流
        FileInputStream fis = new FileInputStream("E:\\software\\IDEA\\JAVASE_mix_01_14\\day08_课堂代码\\捕获.PNG");

        //3.获取Socket输出流
        OutputStream out = socket.getOutputStream();

        byte[] buf = new byte[1024];
        int len;
        //6.循环
        //4.读取文件数据
        while((len=fis.read())!=-1){
            //5.写入到Socket输出了
            out.write(buf,0,len);
        }
        //往Socket的输出流中的写一个结束流
        socket.shutdownOutput();

        //7读取服务端返回的数据
        InputStream in = socket.getInputStream();
        byte[] buf2 = new byte[1024];
        int len2 = in.read(buf2);
        System.out.println("客户端收到: " + new String(buf2,0,len2));

        out.close();
        fis.close();
        socket.close();
    }
}

文件上传的务端流程:

    1.创建服务端,绑定端口
    2.同意客户端的请求
    3.创建文件输出流
    4.获取Socket的输入流
    5.使用Socket的输入流读取数据
    6.使用文件输出流写数据到文件
    7.循环读写
    8.获取Socket的输出流写数据给客户端
    9.关闭流
public class UploadServer {
    public static void main(String[] args) throws IOException {
        System.out.println("服务端启动了。。。");
        //1.创建服务器,绑定端口
        ServerSocket ss = new ServerSocket(10086);

        //2.同意客户端的请求
        Socket s =  ss.accept();
        System.out.println(s.getInetAddress());

        //3.创建文件输出流
        //时间戳(时间的毫秒值)+ 随机数
        Random ran = new Random();
        int i = ran.nextInt(999999999);
        String fileName = "E:\\software\\IDEA\\JAVASE_mix_01_14\\day08_课堂代码\\Test09\\p.png"+System.currentTimeMillis()+"_"+"p.png";

        FileOutputStream fos= new FileOutputStream(fileName);
        //4.获取Socket的输入流
        InputStream in  = s.getInputStream();

        byte[] buf = new byte[1024];
        int len;
        //7.循环读写
        //5.使用Socket的输入流读取数据
        while((len = in.read(buf))!=-1){
            //6.使用文件输出流写数据文件
            fos.write(buf,0,len);
        }

        System.out.println("文件上传结束。。。");

        OutputStream out = s.getOutputStream();
        out.write("上传成功。。。".getBytes());

        //9.关闭流
        out.close();
        in.close();
        fos.close();
        s.close();
        ss.close();

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值