Socket实现文件上传

Socket实现文件上传

文件上传的步骤:

在这里插入图片描述
服务器端步骤:

  1. 创建ServerSocket

  2. 调用accept获得客户端Socket

  3. 定义字节数组

  4. 创建文件输出流,获得客户端输入流

  5. 循环读取输入流的字节,写入到文件输出流

客户端步骤:

  1. 创建Socket

  2. 获得socket对象输出流

  3. 创建文件输入流

  4. 循环读取文件输入流字节,写入到输出流

代码实现:

服务器端:
public class FileServer {
    public static final int PORT = 8888;
    public static final String PATH = "D:\\upload\\";

    public void start(){
        System.out.println("start...");
        try (   //创建服务器端对象
                ServerSocket server = new ServerSocket(PORT);){
            while (true){
                Socket socket = server.accept();
                try (   //创建文件输出流和网络输入流
                        DataInputStream in = new DataInputStream(socket.getInputStream());
                        //读取哭护短发来的文件名,创建文件输出流
                        FileOutputStream out = new FileOutputStream(PATH+in.readUTF())){
                        int len = 0;
                        byte[] buffer = new byte[1024];
                        while ((len = in.read(buffer)) != -1){
                            out.write(buffer,0,len);
                        }
                    System.out.println("服务器保存完毕!");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new FileServer().start();
    }

}
客户端:
public class FileClient {
    /**
     * 发送文件
     */
    public void sendFile(String ip,int port,String path){
        File file = new File(path);
        try (
            //创建连接,创建文件输入流,网络输出流
            Socket socket = new Socket(ip,port);
            InputStream in = new FileInputStream(path);
            DataOutputStream out = new DataOutputStream(socket.getOutputStream())){
            //先发送文件给服务器
            out.writeUTF(file.getName());
            out.flush();
            //读取本地文件,写入到网络输出流中
            int len = 0;
            byte[] buffer = new byte[1024];
            while ((len  = in.read(buffer)) != -1){
                out.write(buffer,0,len);
            }
            System.out.println("客户端发送完毕!");
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new FileClient().sendFile("192.168.31.226",8888,"C:\\Users\\admin\\Desktop\\C.txt");
    }
}
实现效果:

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值