基于TCP通信的简单客户端与服务端小demo—上传文件(二)

本篇文章主要讲解如何将文件上传到服务器

一.服务器的编写

    其过程与一中非常相似,不同点在于:

     1.在此处,我选择了不将服务器关闭,让其一直处于accept的状态

     2.选择了常用的uuid来对文件进行命名,防止重名导致文件被覆盖

     3.开启多线程模式,每来一个上传文件的客户端,就为其开启一个线程,上传完毕后,自动关闭流和线程

注意:因为run方法不能throws异常,因此,此处抛出异常的方式应使用try...catch。代码中,我使用了lombok注释自动抛出

public class UpServer {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket=new ServerSocket(8787);
        while (true){
            Socket socket=serverSocket.accept();
            new Thread(new Runnable() {//开启多线程
                @SneakyThrows
                @Override
                public void run() {
                    InputStream is=socket.getInputStream();
                    File file=new File("C:\\Users\\kjl\\Downloads\\uploads");
                    if(!file.exists())file.mkdirs();
                    UUID uuid=new UUID(0,1111111);
                    String name=file+"\\"+uuid.randomUUID().toString()+".docx";
                   // FileOutputStream fs=new FileOutputStream(file+"\\test2.docx");
                    FileOutputStream fs=new FileOutputStream(name);
                    int len=0;
                    byte[] bytes=new byte[1024];
                    while ((len=is.read(bytes))!=-1)fs.write(bytes,0,len);
                    System.out.println("接收完成");
                    is.close();
                }
            }).start();
        }
       //serverSocket.close();
    }
}

二.客户端的编写

    客户端与之前的基本相同,不同点在于使用的输入流为FileInputStream,其次是使用shutdownOutput关闭socket的输出流,因为在while循环中len不可能为-1。

public class UpClient {
    public static void main(String[] args) throws IOException {
        FileInputStream fs=new FileInputStream("C:\\Users\\kjl\\Downloads\\test.docx");
        Socket socket=new Socket(InetAddress.getLocalHost(),8787);
        OutputStream os=socket.getOutputStream();
        byte[] bytes=new byte[1024];
        int len=0;
        while ((len=fs.read(bytes))!=-1){
            os.write(bytes,0,len);
        }
        socket.shutdownOutput();
        System.out.println("上传成功");
        fs.close();
    }
}

错误之处还请大佬指出,一起学习,一起进步,感谢!

猜你喜欢

转载自blog.csdn.net/lovekjl/article/details/107841400