我是靠谱客的博主 孤独眼神,最近开发中收集的这篇文章主要介绍JAVA通信(1)-- 使用Socket实现文件上传与下载,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

客户端

/**
 * 文件上传客户端
 * 
 * @author chen.lin
 * 
 */
public class UploadClient extends JFrame {

    /**
     * 
     */
    private static final long serialVersionUID = -8243692833693773812L;
    private String ip;// 服务器ip
    private int port;// 端口
    private Properties prop;
    private List<FileBean> fileBeans = new ArrayList<FileBean>();// 从file.xml读到的文件集合
    private Socket socket; // 客户端socket
    private ByteArrayInputStream bais;
    private SequenceInputStream sis;
    private BufferedOutputStream bos;
    private InputStream fs;

    public UploadClient() {

        // 初始化数据
        initDatas();

        // 开始上传文件
        startUploadFile();

        // 设置窗口属性
        initViews();
    }

    private void initViews() {
        setTitle("上传客户端");
        getContentPane().setLayout(null);
        setBounds(160, 200, 440, 300);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setVisible(true);
    }

    /**
     * 开始上传文件....
     */
    public void startUploadFile() {
        try {
            socket = new Socket(ip, port);
            if (!socket.isClosed() && socket.isConnected()) {
                Logger.log("客户端连接成功....");
                System.out.println("客户端连接成功....");
            } else {
                Logger.log("连接失败, 请与开发人员联系....");
                JOptionPane.showMessageDialog(null, "连接失败, 请与开发人员联系");
                return;
            }

            for (FileBean fileBean : fileBeans) {
                String filePath = fileBean.getPath();
                Logger.log("filepath===" + filePath);
                File file =  null;
                if (filePath != null && !"".equals(filePath.trim())) {
                    int indexOf = filePath.lastIndexOf("/");
                    String fileName = filePath.substring(indexOf + 1);

                    if (filePath.startsWith("http://")) {
                        URL url = new URL(filePath);
                        file = new File(filePath);
                        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                        conn.setReadTimeout(5000);
                        conn.setRequestMethod("GET");
                        conn.setConnectTimeout(5000);
                        if (conn.getResponseCode() == 200) {
                            fs = conn.getInputStream();
                        }else {
                            Logger.log("错误信息:文件网络路径错误:" + filePath);
                        }
                    }else {
                        file = new File(fileBean.getPath());
                        fs = new FileInputStream(file);
                    }
                    Logger.log("filename=" + fileName);
                    long fileSize = file.length();
                    Logger.log("filesize===" + fileSize);
                    if (fileSize / 1024 / 1024 > 70) {
                        Logger.log("文件超过了70M,不能上传");
                        return;
                    }
                    //定义一个256字节的区域来保存文件信息。
                    byte[] b = fileName.getBytes();
                    byte[] info = Arrays.copyOf(b, 256);
                    bais = new ByteArrayInputStream(info);
                    sis = new SequenceInputStream(bais, fs);

                    if (socket.isClosed()) {
                        Logger.log("重新连接成功!");
                        System.out.println("重新连接成功!");
                        socket = new Socket(ip, port);
                    }

                    bos = new BufferedOutputStream(socket.getOutputStream());
                    BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                    byte[] buf = new byte[1024];
                    int len = 0;
                    while ((len = sis.read(buf)) != -1) {
                        bos.write(buf, 0, len);
                        bos.flush();
                    }
                    //关闭
                    socket.shutdownOutput();

                    String result = br.readLine();
                    Logger.log(fileBean.getName() + "上传:" + result);
                    if ("success".equals(result.trim())) {
                        fileBean.setState(1);
                        XmlUtil.changeFileState(prop.getProperty("xmlPath"), fileBean);
                    }
                    br.close();
                }

            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bos != null) {
                    bos.close();
                }
                if (sis != null) {
                    sis.close();
                }
                if (fs != null) {
                    fs.close();
                }
                if (bais != null) {
                    bais.close();
                }
                if (socket != null) {
                    socket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 初始化数据
     * 
     * @throws UnknownHostException
     * @throws Exception
     */
    private void initDatas() {
        try {
            prop = PropUtil.getProp();
            ip = prop.getProperty("ip");
            if (ip.startsWith("http://")) {
                ip = InetAddress.getByName(ip).getHostAddress();
            }
            port = Integer.parseInt(prop.getProperty("port"));
            final String xmlPath = prop.getProperty("xmlPath");
            Logger.log("xmlPath===" + xmlPath);
            System.out.println("xmlPath===" + xmlPath);
            // 因为读的是远程xml,比较耗时,所以放在线程里运行
            ExecutorService executorService = Executors.newCachedThreadPool();
            ArrayList<Future<List<FileBean>>> list = new ArrayList<Future<List<FileBean>>>();
            list.add(executorService.submit(new CallThread(xmlPath)));
            for (Future<List<FileBean>> fs : list) {
                List<FileBean> fileBean = fs.get();
                fileBeans.addAll(fileBean);
            }

        } catch (Exception e) {
            e.printStackTrace();
            Logger.log("error:" + e.getMessage());
            //JOptionPane.showMessageDialog(null, "error:" + e.getMessage());
        }
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    new UploadClient();
                    System.exit(0);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

}

服务器端代码

/**
 * 文件上传服务器端
 * 
 * @author chen.lin
 * 
 */
public class UploadServer extends JFrame {
    /**
     * 
     */
    private static final long serialVersionUID = -5622620756755192667L;
    private JTextField port;
    private ServerSocket server;
    private volatile boolean isRun = false;
    private ExecutorService pool = Executors.newFixedThreadPool(10);

    public UploadServer() {
        setTitle("上传服务器");
        getContentPane().setLayout(null);

        JLabel label = new JLabel("监听窗口:");
        label.setBounds(86, 80, 74, 15);
        getContentPane().add(label);

        port = new JTextField("9000");
        port.setBounds(178, 77, 112, 21);
        getContentPane().add(port);
        port.setColumns(10);
        /**
         * 启动服务
         */
        final JButton btnStart = new JButton("启动服务器");
        btnStart.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                port.setEnabled(false); // 控件黑白不可变
                btnStart.setEnabled(false);
                isRun = true;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            server = new ServerSocket(Integer.parseInt(port.getText()));
                            System.out.println("服务器开始启动了........");
                            while (isRun) {
                                pool.execute(new UploadThread(server.accept()));
                            };
                        } catch (NumberFormatException e1) {
                            e1.printStackTrace();
                        } catch (IOException e1) {
                            e1.printStackTrace();
                            pool.shutdown();
                        }
                    }
                }).start();
            }
        });
        btnStart.setBounds(73, 145, 93, 23);
        getContentPane().add(btnStart);

        JButton btnStop = new JButton("停止服务器");
        btnStop.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                port.setEnabled(true);
                btnStart.setEnabled(true);
                isRun = false;
                server = null;
            }
        });
        btnStop.setBounds(209, 145, 93, 23);
        getContentPane().add(btnStop);
        setBounds(600, 200, 380, 300);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    new UploadServer();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 进行文件传输耗内存,所以必须放在线程中运行
     */
    class UploadThread implements Runnable {
        private Socket socket;
        private SimpleDateFormat sdf;
        private BufferedInputStream bis;
        private BufferedOutputStream bos;

        UploadThread(Socket socket) {
            this.socket = socket;
            sdf = new SimpleDateFormat("yyyyMMddHH");
        }

        @Override
        public void run() {
            try {
                bis = new BufferedInputStream(socket.getInputStream());
                byte[] info = new byte[256];
                bis.read(info);
                String fileName = new String(info).trim();
                String filePath = PropUtil.getProp().getProperty("filePath");
                String fullPath = filePath + "/" + sdf.format(new Date());
                File dirs = new File(fullPath);
                if (!dirs.exists()) {
                    dirs.mkdirs();
                }

                PrintWriter pw = new PrintWriter(socket.getOutputStream(),true);
                if (!TextUtil.isEmpty(fileName)) {
                    bos = new BufferedOutputStream(new FileOutputStream(fullPath  + "/" + fileName));
                    byte[] buf = new byte[1024];
                    int len = 0;
                    while ((len = bis.read(buf)) != -1) {
                        bos.write(buf, 0, len);
                        bos.flush();
                    }

                    System.out.println(fileName + "  文件传输成功");

                    pw.println("success");
                }else {
                    pw.println("failure");
                }
                pw.close();

            } catch (IOException e) {
                e.printStackTrace();
            } finally{
                try {
                    if (bos != null) {
                        bos.close();
                    }
                    if (bis != null) {
                        bis.close();
                    }
                    if (socket != null) {
                        socket.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

相关的工具类

/**
 * 记录日志信息
 * @author chen.lin
 *
 */
public class Logger {

    public static void log(String name){
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHH");
            String path = "d:/upload_log/" + sdf.format(new Date()) ;
            File file = new File(path);
            if (!file.exists()) {
                file.mkdirs();
            }
            FileOutputStream out = new FileOutputStream(new File(path + "/log.txt"), true);
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out));
            bw.write(name + "rn");
            bw.flush();
            bw.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
/**
 * 读取配置文件工具
 * @author chen.lin
 *
 */
public class PropUtil {

    private static Properties prop;
    static{
        prop = new Properties();
        //InputStream inStream = PropUtil.class.getClassLoader().getResourceAsStream("d:/files/config.properties");
        try {
            InputStream inStream = new FileInputStream(new File("d:/files/config.properties"));
            prop.load(inStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Properties getProp(){
        return prop;
    }


    public static void main(String[] args) {
        String xmlPath = (String) PropUtil.getProp().get("filePath");
        System.out.println(xmlPath);
    }
}
/**
 * 文本工具
 * @author chen.lin
 *
 */
public class TextUtil {

    public static boolean isEmpty(String text){
        if (text == null || "".equals(text.trim())) {
            return true;
        }
        return false;
    }
}
/**
 * xml文件解析与生成
 * 
 * @author chen.lin
 * 
 */
public class XmlUtil {

    /**
     * 从xml文件中获取文件信息
     * 
     * @param xmlPath
     * @return
     * @throws Exception
     */
    public static List<FileBean> getFileBeanFromXml(String xmlPath) throws Exception {
        List<FileBean> list = null;
        if (TextUtil.isEmpty(xmlPath)) {
            return null;
        }
        XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
        XmlPullParser parser = factory.newPullParser();
        InputStream inputStream = null;
        if (xmlPath.startsWith("http://")) {
            URL url = new URL(xmlPath);
            inputStream = url.openStream();
        } else {
            inputStream = new FileInputStream(new File(xmlPath));
        }
        parser.setInput(inputStream, "UTF-8");
        int eventType = parser.getEventType();
        FileBean bean = null;
        while (eventType != XmlPullParser.END_DOCUMENT) {
            switch (eventType) {
            case XmlPullParser.START_DOCUMENT:
                list = new ArrayList<FileBean>();
                break;
            case XmlPullParser.START_TAG:
                if ("file".equals(parser.getName())) {
                    bean = new FileBean();
                    bean.setId(parser.getAttributeValue(0));
                } else if ("name".equals(parser.getName())) {
                    bean.setName(parser.nextText());
                } else if ("path".equals(parser.getName())) {
                    bean.setPath(parser.nextText());
                } else if ("state".equals(parser.getName())) {
                    int state = Integer.parseInt(parser.nextText());
                    bean.setState(state);
                }
                break;
            case XmlPullParser.END_TAG:
                // 添加对象到list中
                if ("file".equals(parser.getName()) && bean != null && bean.getState() == 0) {
                    list.add(bean);
                    bean = null;
                }
                break;
            }
            // 当前解析位置结束,指向下一个位置
            eventType = parser.next();
        }
        return list;
    }

    /**
     * 修改xml内容
     * 
     * @param xmlPath
     * @param bean
     */
    public static void changeFileState(String xmlPath, FileBean bean) {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = null;
            if (xmlPath.startsWith("http://")) {
                URL url = new URL(xmlPath);
                doc = db.parse(url.openStream());
            } else {
                doc = db.parse(new File(xmlPath));
            }
            NodeList list = doc.getElementsByTagName("file");// 根据标签名访问节点
            for (int i = 0; i < list.getLength(); i++) {// 遍历每一个节点
                Element element = (Element) list.item(i);
                String id = element.getAttribute("id");
                if (id.equals(bean.getId())) {
                    element.getElementsByTagName("state").item(0).getFirstChild().setNodeValue(bean.getState()+"");
                }
            }
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource domSource = new DOMSource(doc);
            // 设置编码类型
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            StreamResult result = new StreamResult(new FileOutputStream(xmlPath));
            transformer.transform(domSource, result);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 生成新的xml文件
     * 
     * @param xmlPaht
     */
    public static void createFileXml(String xmlPath, FileBean bean) throws Exception {
        XmlSerializer seria = XmlPullParserFactory.newInstance().newSerializer();
        OutputStream out = null;
        if (xmlPath.startsWith("http://")) {
            URL url = new URL(xmlPath);
            URLConnection conn = url.openConnection();
            out = conn.getOutputStream();
        } else {
            out = new FileOutputStream(new File(xmlPath));
        }
        seria.setOutput(out, "UTF-8"); // 设置输出方式,这里使用OutputStream,编码使用UTF-8
        seria.startDocument("UTF-8", true); // 开始生成xml的文件头
        seria.startTag(null, "files");
        seria.startTag(null, "file");
        seria.attribute(null, "id", bean.getId().toString()); // 添加属性,名称为id
        seria.startTag(null, "name");
        seria.text(bean.getName().toString()); // 添加文本元素
        seria.endTag(null, "name");
        seria.startTag(null, "path");
        seria.text(String.valueOf(bean.getPath()));// 这句话应该可以用来
        seria.endTag(null, "path");
        seria.startTag(null, "state");
        seria.text(bean.getState() + "");
        seria.endTag(null, "state");
        seria.endTag(null, "file");
        seria.endTag(null, "files"); // 标签都是成对的
        seria.endDocument();
        out.flush();
        out.close(); // 关闭输出流
    }

    public static void main(String[] args) throws Exception {
        String xmlPath = PropUtil.getProp().getProperty("xmlPath");
        FileBean bean = new FileBean();
        bean.setId("1");
        bean.setState(1);
        XmlUtil.changeFileState(xmlPath, bean);

        /*
         * List<FileBean> list = XmlUtil.getFileBeanFromXml(xmlPath); for (FileBean bean : list) { System.out.println(bean.getName()); }
         */
    }

}

实体类

/**
 * 文件bean
 * 
 * @author chenlin
 * 
 */
public class FileBean {

    private String id; //id
    private String name;//文件名称
    private String path;//文件路径
    private int state;//上传结果0未上传,1已经上传,2上传错误


    public FileBean() {
    }

    public FileBean(String id, int state) {
        this.id = id;
        this.state = state;
    }

    public FileBean(String id, String name, String path, int state) {
        this.id = id;
        this.name = name;
        this.path = path;
        this.state = state;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public int getState() {
        return state;
    }

    public void setState(int state) {
        this.state = state;
    }

    @Override
    public String toString() {
        return "FileBean [id=" + id + ", name=" + name + ", path=" + path + ", state=" + state + "]";
    }



}

回调函数

class CallThread implements Callable<List<FileBean>> {
    private String xmlPath;

    public CallThread(String xmlPath) {
        this.xmlPath = xmlPath;
    }

    @Override
    public List<FileBean> call() throws Exception {
        return XmlUtil.getFileBeanFromXml(xmlPath);
    }
}

———————————————————————
(java 架构师全套教程,共760G, 让你从零到架构师,每月轻松拿3万)
有需求者请进站查看,非诚勿扰

https://item.taobao.com/item.htm?spm=686.1000925.0.0.4a155084hc8wek&id=555888526201

01.高级架构师四十二个阶段高
02.Java高级系统培训架构课程148课时
03.Java高级互联网架构师课程
04.Java互联网架构Netty、Nio、Mina等-视频教程
05.Java高级架构设计2016整理-视频教程
06.架构师基础、高级片
07.Java架构师必修linux运维系列课程
08.Java高级系统培训架构课程116课时
(送:hadoop系列教程,java设计模式与数据结构, Spring Cloud微服务, SpringBoot入门)
——————————————————————–

最后

以上就是孤独眼神为你收集整理的JAVA通信(1)-- 使用Socket实现文件上传与下载的全部内容,希望文章能够帮你解决JAVA通信(1)-- 使用Socket实现文件上传与下载所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(41)

评论列表共有 0 条评论

立即
投稿
返回
顶部