package com.chenyang.nse.bussiness.tools.ha;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import org.apache.commons.lang.StringUtils;

public class TcpServer extends Thread {
   private int port;

   public TcpServer(int port) {
      this.port = port;
   }

   public void run() {
      System.out.println(">>>>>>>>>>>>>>TcpServer has start>>>>>>>>>>>>>>");
      Socket socket = null;
      DataInputStream socketinput = null;
      DataOutputStream fileOut = null;
      DataOutputStream socketout = null;
      int bufferSize = 8192;
      byte[] buf = new byte[bufferSize];
      long donelen = 0L;
      long filelen = 0L;

      try {
         System.out.println("等待连接");
         ServerSocket listen = new ServerSocket(this.port);

         while(true) {
            String filePath = "";

            try {
               socket = listen.accept();
               socket.setSoTimeout(20000);
               System.out.println("客户端" + socket.getInetAddress() + "已连接");
               socketinput = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
               String flg = "";
               String pathStr = "";

               try {
                  flg = socketinput.readUTF();
                  System.out.println(">>>>>>flg:" + flg);
                  if (StringUtils.isBlank(flg)) {
                     System.out.println("同步类型不能为空！");
                     continue;
                  }

                  pathStr = socketinput.readUTF();
               } catch (Exception var141) {
               }

               if (StringUtils.isBlank(pathStr)) {
                  System.out.println("客户端发送文件路径为空！");
               } else {
                  String[] pathArr = pathStr.split("#");
                  if (null != pathArr && pathArr.length >= 2) {
                     String fileName = pathArr[1];
                     String path = pathArr[0];
                     File dirfile = new File(path);
                     System.out.println("客户端发送文件路径为：" + path);
                     if ("1".equals(flg)) {
                        if (dirfile.exists()) {
                           System.out.println("之前存在该目录，需要先删除目录并重建！");
                           deleteDir(dirfile);
                           dirfile.mkdir();
                        } else {
                           System.out.println("之前不存在该目录，需要创建该目录！");
                           dirfile.mkdir();
                        }
                     }

                     if (!dirfile.exists()) {
                        dirfile.mkdir();
                     }

                     filePath = path + "/" + fileName;
                     File file = new File(filePath);
                     if (!file.exists()) {
                        file.createNewFile();
                     }

                     System.out.println("客户端发送文件为：" + filePath);
                     filelen = socketinput.readLong();
                     System.out.println("文件的长度为:" + filelen + "\n");
                     System.out.println("开始接收文件!\n");
                     socketout = new DataOutputStream(socket.getOutputStream());
                     fileOut = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
                     donelen = 0L;

                     do {
                        int readLen = 0;
                        if (socketinput != null) {
                           readLen = socketinput.read(buf);
                           if (readLen == -1) {
                              System.out.println("读取客户端传送文件，并写入到本地文件中完成..");
                              break;
                           }

                           System.out.println("读取要下载文件的大小readLen：" + readLen);
                        }

                        donelen += (long)readLen;
                        System.out.println("文件接收了" + donelen * 100L / filelen + "%\n");
                        fileOut.write(buf, 0, readLen);
                        System.out.println("donelen:" + donelen + " filelen:" + filelen);
                     } while(donelen != filelen);

                     System.out.println("finish :donelen:" + donelen + " filelen:" + filelen);
                     if (donelen == filelen) {
                        System.out.println("接收完成，文件存为" + file + "\n");
                     } else {
                        System.out.printf("IP:%s发来的%s传输过程中失去连接,传输文件存在文件丢失情况\n", socket.getInetAddress(), fileName);
                     }
                  } else {
                     System.out.println("客户端发送文件路径格式不正确(缺少路径或者文件名)！");
                  }
               }
            } catch (Exception e) {
               System.out.println("接收消息错误\n");
               e.printStackTrace();
            } finally {
               try {
                  System.out.println("filePath:" + filePath);
                  String returnStr = "0";
                  if (donelen == filelen) {
                     returnStr = "1";
                  }

                  socketout.writeUTF(returnStr);
               } catch (Exception var139) {
               } finally {
                  if (null != fileOut) {
                     fileOut.close();
                  }

                  if (null != socketout) {
                     socketout.close();
                  }

                  if (null != socketinput) {
                     socketinput.close();
                  }

                  if (null != socket) {
                     socket.close();
                  }

               }

            }
         }
      } catch (Exception e) {
         System.out.println("接收消息错误\n");
         e.printStackTrace();
         System.out.println(">>>>>>>>>>>>>>TcpServer has end>>>>>>>>>>>>>>");
      }
   }

   private static boolean deleteDir(File dir) {
      if (dir.isDirectory()) {
         String[] children = dir.list();

         for(int i = 0; i < children.length; ++i) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
               return false;
            }
         }
      }

      return dir.delete();
   }

   public static void main(String[] args) {
      TcpServer server = new TcpServer(8888);
      server.start();
   }
}
