java
主页 > 软件编程 > java >

java使用Socket实现文件上传功能的代码

2022-02-24 | 秩名 | 点击:

文件上传的步骤:

服务器端步骤:

1、创建ServerSocket

2、调用accept获得客户端Socket

3、定义字节数组

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

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

客户端步骤:

1、创建Socket

2、获得socket对象输出流

3、创建文件输入流

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

代码实现:

服务器端:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

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();

    }

 

}

客户端:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

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");

    }

}

实现效果:

原文链接:https://blog.csdn.net/weixin_44889894/article/details/116591759
相关文章
最新更新