xsocket 实现上传和解压文件

引入 xsocket 相关jar

第一步:创建接受数据的类SocketHandler
package com.socket;

import java.io.IOException;
import java.nio.BufferUnderflowException;
import java.nio.channels.ClosedChannelException;

import org.xsocket.MaxReadSizeExceededException;
import org.xsocket.connection.IConnectExceptionHandler;
import org.xsocket.connection.IConnectHandler;
import org.xsocket.connection.IDataHandler;
import org.xsocket.connection.IDisconnectHandler;
import org.xsocket.connection.INonBlockingConnection;

public class SocketHandler implements IConnectHandler,IDisconnectHandler,IDataHandler,IConnectExceptionHandler{

@Override
public boolean onDisconnect(INonBlockingConnection nbc) throws IOException {

return false;
}

@Override
public boolean onConnectException(INonBlockingConnection nbc,
IOException arg1) throws IOException {
return false;
}

@Override
public boolean onData(INonBlockingConnection nbc) throws IOException,
BufferUnderflowException, ClosedChannelException,
MaxReadSizeExceededException {
try{

if (nbc.available() == -1) {
return false;
}

// 接受文件
SocketService.acceptFile(nbc);
// 解压
SocketService.jieyaFile();

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

return true;
}

@Override
public boolean onConnect(INonBlockingConnection nbc) throws IOException,
BufferUnderflowException, MaxReadSizeExceededException {
System.out.println(nbc.getRemoteAddress()+" 来访!");
return false;
}

}

第二步: 创建服务端类SocketServer

package com.socket;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.concurrent.TimeUnit;

import org.xsocket.WorkerPool;
import org.xsocket.connection.IServer;
import org.xsocket.connection.Server;

public class SocketServer {

 private static IServer server = null;
 
 private static final int PORT = 2049;
 
 public static void start() {
  
  try {
   server = new Server(PORT,new SocketHandler());
   
   server.setAutoflush(false);
   
   // minSize, maxSize, keepalive, timeunit, taskqueuesize, isDaemon
   WorkerPool workerPool = new WorkerPool(200, 1000, 1800, TimeUnit.SECONDS, 1000, false);
   // 预启动所有核心线程
   workerPool.prestartAllCoreThreads();
   
   server.setWorkerpool(workerPool);
   
   server.start();
   
   System.out.println("Test SocketServer Started...");
   
  } catch (UnknownHostException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
 
 public static void stop() {
  if (server != null && server.isOpen()) {
   try {
    server.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }
 
 public static void main(String[] args) {
  
  start();
 }
}

第三步:创建处理业务逻辑的类SocketService

package com.socket;

import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import org.xsocket.connection.INonBlockingConnection;
import org.xsocket.connection.NonBlockingConnection;

public class SocketService {

 public static final byte[] buf = new byte[1024];

 public static final int port = 2049;
 
 private static final int BYTE_LENGTH = 1024;
 
 public static final String filePath = "d:\\testzip3.zip";
 
 public static final String zipFilePath = "d:\\testzip3";
 
 public static File zipFile;

 public static void test() {
  
  INonBlockingConnection nbc = null;
  
  try {
   System.out.println("连接中...");
   nbc = new NonBlockingConnection("192.168.1.49",port ,new SocketHandler());
   nbc.write("123");
  } catch (IOException e) {
   System.out.println("SocketService异常");
   e.printStackTrace();
  }
 }
 
 /**
  * 上传文件
  * @param remoteAddr 远程服务器地址
  * @param filePath 要上传的文件地址
  */
 public static void uploadFile(String remoteAddr, String filePath) {

  INonBlockingConnection nbc = null;

  DataInputStream dis = null;
  try {  
   // 连接
   nbc = new NonBlockingConnection(remoteAddr,port ,new SocketHandler());

   dis = new DataInputStream(new FileInputStream(new File(filePath)));

   int len = 0 ;
   
   while ((len=dis.read(buf)) != -1) {
    nbc.write(buf, 0, len);
   }
  } catch (UnknownHostException e) {  
   e.printStackTrace();  
  } catch (IOException e) {  
   e.printStackTrace();  
  } finally {  
   if (dis != null) {
    try {
     dis.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
   if (nbc != null) {
    try {
     nbc.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }  
 }
 
 /**
  * 接受文件
  * */
 public static void acceptFile(INonBlockingConnection nbc) {
  
  try {
   // 创建一个字节缓冲区
   ByteBuffer byteBuffer = ByteBuffer.allocate(BYTE_LENGTH);
   zipFile = new File(filePath);
   DataOutputStream output = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));
   int len = 0;
   while ((len = nbc.read(byteBuffer)) != -1) {
    output.write(byteBuffer.array(),0,len);
    // 清理缓冲区
    byteBuffer.clear();
   }
   if (output != null) {
    try {
     output.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
   System.out.println("文件上传成功!");
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
 
 /**
  * @param targetFile 要解压的文件
  * @param zipPath 解压路径
  * 不支持中文文件名
  */
 public static void jieyaFile() {

  ZipInputStream zis= null;
  FileOutputStream fos = null;
  try {

   // 判断目录是否存在
   File zipPathFile = new File(zipFilePath);
   if (!zipPathFile.exists()) {
    zipPathFile.mkdir();
   }

   zis = new ZipInputStream(new FileInputStream(new File(filePath)));
   
   ZipEntry entry = null;
   
   while ((entry=zis.getNextEntry())!=null) {
    File file = new File(zipFilePath+File.separator+entry.getName());
    // 是否是目录
    if(entry.isDirectory()) {
     file.mkdir();
    } else {
     fos = new FileOutputStream(file);
     int len =0;
     while ((len = zis.read(buf)) != -1) {
      fos.write(buf,0,len);
     }
     if (fos !=null) {
      fos.close();
     }
    }
   }
   System.out.println("文件解压成功!");
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   if (zis != null) {
    try {
     zis.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
 }

 public static void main(String[] args) {
  
  //test();
  
  uploadFile("192.168.1.49", "d:\\testzip.zip");
 }
}

// 测试  进入命令行输入:telnet ip port


原文地址:https://www.cnblogs.com/cuker919/p/4878555.html