⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 sendfilethread.java

📁 JAVA实现的网络服务器文件同步
💻 JAVA
字号:
package com.msd;

import java.io.*;
import java.util.*;
import java.net.*;
import sun.misc.*;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;

public class SendFileThread implements Runnable {
	
	private String userName = "MSDWAP";
	private String password = "GTimeFileSend";
	private String SALT = "3GHficCedsVbR+956-ONjWNoKis4sBt9";
	private static final String[] hexDigits = {
      "0", "1", "2", "3", "4", "5", "6", "7",
      "8", "9", "a", "b", "c", "d", "e", "f"};
	private int soTimeout = 30000;
	private String imgPath = "F:/upload/img/source/";
	private String audioPath = "F:/upload/sing/";
	private String jarPath = "F:/upload/jar/";
	private String newsPath = "D:/news/images/";
	private List fileList = null;
	private String server = null;
	private int port = 0;
	private int key = 0;
	
	public SendFileThread(String serveradd,int portid,int i) {
		this.server = serveradd;
		this.port = portid;	
		this.key = i;
		fileList = new LinkedList();
	}
	
	public void run() {
		try {
			while(true) {
				if(fileList.isEmpty()) {
					try {
						Thread.sleep(5000L);
					} catch(Exception e) {	}
					readFileList();				
				} else {
					sendFile();	
				}
			}		
		} catch(Exception e) {
			Log.logger.error("SendFileThread run Error: " + e.toString());		
			(SendFileThreadFactory.getInstance()).ExceptionOut(key);
		}	
	}
	//=================发送文件====================//
	private void sendFile() {
		Socket socket = null;
		DataInputStream in = null;
		DataOutputStream out = null;
		
		try {
			socket = new Socket(server,port);
		} catch (Exception e) {
			Log.logger.error("SendFileThread sendFile Socket Error:" + e.toString());
			return;
		}
		
		try {
			socket.setSoTimeout(soTimeout);
			in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
			out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
		} catch(Exception e) {
			Log.logger.error("SendFileThread createIO Error :" + e.toString());
			if(in != null) {
				try {
					in.close();
					in = null;
				} catch(Exception e1) { }
			}
			if(out != null) {
				try {
					out.close();
					out = null;
				} catch(Exception e2) { }
			}
			try {
				socket.close();
				socket = null;
			} catch(Exception e3) { }
			return;
		}
		
		try {
			byte[] bindPSD = getPSD();
			byte[] bind = new byte[bindPSD.length + 8];
			appendInt(bind.length,bind,0);
			appendInt(0x1,bind,4);
			for(int b = 0;b < bindPSD.length;b++)
				bind[8 + b] = bindPSD[b];
				
			out.write(bind,0,bind.length);
       		out.flush();

			int len = in.readInt();
			int comd = in.readInt();
			byte state = in.readByte();
			
			if(len == 9 && comd == 0x11 && state == (byte)0) {
						
			} else {
				Log.logger.error("SendFileThread bind wrong!!");
				try {
					in.close();
					in = null;
				} catch(Exception e1) { }
				try {
					out.close();
					out = null;
				} catch(Exception e2) { }
				try {
					socket.close();
					socket = null;
				} catch(Exception e3) { }
				return;
			}
		} catch(Exception e) {
			Log.logger.error("SendFileThread bind Error:" + e.toString());	
			try {
				in.close();
				in = null;
			} catch(Exception e1) { }
			try {
				out.close();
				out = null;
			} catch(Exception e2) { }
			try {
				socket.close();
				socket = null;
			} catch(Exception e3) { }
			return;
		}
		
		while(true) {
			try {
				if(fileList.isEmpty())
					break;
				SendFile sf = (SendFile)fileList.get(0);
				byte[] fileByte = readFile(sf.fileName,sf.flag);
				
				if(fileByte == null) {
					fileList.remove(0);	
					continue;
				}
								
				byte[] fileMd5 = (MD5Encode(fileByte)).getBytes();
				byte[] send = new byte[9 + 20 + fileByte.length + fileMd5.length];
				
				appendInt(send.length,send,0);
				appendInt(0x3,send,4);
				for(int i = 0 ;i < fileMd5.length; i++) 
					send[8 + i] = fileMd5[i];
				
				appendString(sf.fileName,20,send,8 + fileMd5.length);
					
				send[8 + fileMd5.length + 20] = (byte)sf.flag;	
					
				for(int i = 0 ;i < fileByte.length; i++) 
					send[9 + fileMd5.length + 20 + i] = fileByte[i];
			
				out.write(send,0,send.length);
       			out.flush();
       			
				int lenT = in.readInt();
				int comdT = in.readInt();
				byte stateT = in.readByte();

				if(lenT == 9 && comdT == 0x13 && stateT == (byte)0) {
					fileList.remove(0);
					Log.logger.info("SendFile Success:" + sf.fileName);
					send = null;
					fileMd5 = null;	
					fileByte = null;
					sf = null;
					continue;
				} else {
					Log.logger.info("SendFile Lost:" + sf.fileName);
					send = null;
					fileMd5 = null;	
					fileByte = null;
					sf = null;
					continue;
				}
			} catch(Exception e) {
				Log.logger.error("SendFileThread sendFile Error: " + e.toString());
				break;
			}		
	    }
	    
	    try {
	    	byte[] end = new byte[8];
	    	appendInt(8,end,0);
	    	appendInt(0x2,end,4);
	    	
	    	out.write(end,0,end.length);
	    	out.flush();	    		
	    } catch(Exception e) {
	    	Log.logger.error("SendFileThread close Error: " + e.toString());
	    } finally {
			try {
				in.close();
				in = null;
			} catch(Exception e1) { }
			try {
				out.close();
				out = null;
			} catch(Exception e2) { }
			try {
				socket.close();
				socket = null;
			} catch(Exception e3) { }
	    }
	}
	
	private void appendInt(int v,byte[] b,int i) {
		b[i + 0] = (byte)((v >>> 24) & 0xFF);
		b[i + 1] = (byte)((v >>> 16) & 0xFF);
		b[i + 2] = (byte)((v >>> 8 ) & 0xFF);
		b[i + 3] = (byte)((v >>> 0 ) & 0xFF);
	}
	
	private void appendString(String s,int len,byte[] b,int i) {
		if(s == null || s.equals("")) {
			for(int j = 0 ; j < len ; j++)
				b[i + j] = '\0';
		} else {
			byte[] v = s.getBytes();
			for(int j = 0 ; j < len ; j++) {
				if(v.length > j)
					b[i + j] = v[j];
				else 
					b[i + j] = '\0';
			}
		} 
	}   
	
	//=================END=========================//
	//=================获得加密验证================//
	private byte[] getPSD() {
		StringBuffer tmp = new StringBuffer("");
		tmp.append(userName).append("$");
		tmp.append((Calendar.getInstance()).getTimeInMillis()).append("$");
		tmp.append(password);
		return 	encryptMode(getFromBASE64(SALT),(tmp.toString()).getBytes());	
	}	
	//=================END=========================//
	//=================读取文件列表================//
	private void readFileList() {
		while(true) {
			SendFile fileName = (FileDisList.getInstance()).getFileName(key);	
			if(fileName == null)
				break;
			else 
				fileList.add(fileList.size(),fileName);
		}		
	}	
	//=================END=========================//
	//=================读取文件====================//
	private byte[] readFile(String fileName,int flag) {
		try {
			StringBuffer filePath = new StringBuffer("");
			switch(flag) {
				case 1 : filePath.append(imgPath).append(fileName.trim());	break;	
				case 2 : filePath.append(audioPath).append(fileName.trim());	break;
				case 3 : filePath.append(jarPath).append(fileName.trim());	break;
				case 4 : filePath.append(newsPath).append(fileName.trim()); 	break;
				case 5 : byte[] tmpd = new byte[1];
						 tmpd[0] = (byte)0;
						 return tmpd;
			}	
			FileInputStream info = new FileInputStream(new File(filePath.toString()));	
			byte[] tmp = new byte[info.available()];
		
			int n = info.read(tmp); //不安全的文件读取方法
			
			info.close();
			info = null;
			return tmp;			
		} catch(Exception e) {
			Log.logger.error("SendFileThread readFile[" + fileName +"] Error: " + e.toString());
			return null;		
		}
	}	
	//=================END=========================//
	//=================加密验证====================//
	public byte[] getFromBASE64(String rn) {
		if(rn == null) 
			return null;
	 	BASE64Decoder decoder = new BASE64Decoder();
	  	try {
	    	return decoder.decodeBuffer(rn);
	  	} catch (Exception e) {
	    	return null;
	  	}
	}
	
    public byte[] encryptMode(byte[] keybyte,byte[] src) {
		try {
		    SecretKey deskey = new SecretKeySpec(keybyte,"DESede");
		    Cipher ci = Cipher.getInstance("DESede");
		    ci.init(Cipher.ENCRYPT_MODE,deskey);
		    return ci.doFinal(src);
		} catch (java.security.NoSuchAlgorithmException e1) {
		    Log.logger.error("SendFileThread encryptMode Error1: " + e1.toString());
		} catch (javax.crypto.NoSuchPaddingException e2) {
		    Log.logger.error("SendFileThread encryptMode Error2: " + e2.toString());
		} catch (java.lang.Exception e3) {
		    Log.logger.error("SendFileThread encryptMode Error3: " + e3.toString());
		}
		return null;
    }
    
	private String byteArrayToHexString(byte[] b) {
		StringBuffer resultSb = new StringBuffer();
		for (int i = 0; i < b.length; i++) {
			resultSb.append(byteToHexString(b[i]));
		}
		return resultSb.toString();
	}
	
	private String byteToHexString(byte b) {
		int n = b;
		if (n < 0)
			n = 256 + n;
		int d1 = n / 16;
		int d2 = n % 16;
		return hexDigits[d1] + hexDigits[d2];
	}
	
	private String MD5Encode(byte[] source) {
		String resultString = "";
		try {
		  MessageDigest md = MessageDigest.getInstance("MD5");
		  resultString = byteArrayToHexString(md.digest(source));
		} catch (Exception ex) {  }
		return resultString;
	}
	//=================END=========================//
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -