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

📄 ftpserver.java

📁 j2se 平台开发的简单ftp service 代码 学习之用,仅供参考
💻 JAVA
字号:
package Server;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import Client.Message;

public class FTPServer implements Runnable{
	
	private Socket client;
	private Thread theThread;
	private static int count;
	private static ThreadGroup threadGroup;
	private static String currentpath=null; 
	private static String file=null;
	private static String prePath=null;
	private static SessionManager sm = new SessionManager();
	private static String sessionId = null;
	private static boolean logFlag = false;
	
	public FTPServer(Socket s)
	{
		client=s;
		theThread=new Thread(threadGroup,this,"Socket"+count);
		System.out.println("Socket"+count);
		count++;
		theThread.start();
	}
	public void run() {
		//set inital Path
		prePath=currentpath="d:/"; //Original Path,will initial the path in hashtable when Login OK
		ObjectInputStream sockin=null;
		ObjectOutputStream sockout=null;
		//Message clientword=new Message();
		try {
			sockin=new ObjectInputStream(client.getInputStream());
			sockout=new ObjectOutputStream(client.getOutputStream());			
		} catch (IOException e) {
			e.printStackTrace();
		}
		while(true)//循环取指令
			
		{	
			//socketin object-Message Parse
			String inType = null;
			String inCmd = null;
			ArrayList inParas = new ArrayList(); 
			Message clientword=new Message();
			try {
				clientword =(Message)sockin.readObject();
				inType = clientword.type;
				inCmd = clientword.command;
				inParas = clientword.paras;
				//test socketin object Message
				System.out.print(inCmd);
//				System.out.print(inParas.get(0));
//				System.out.print(inParas.get(1));
				System.out.print(inType);
				//System.out.print(sockin.available());
			} catch (IOException e1) {
				e1.printStackTrace();
			}catch(ClassNotFoundException e2)
			{
				e2.printStackTrace();
			}
			
			//1-login 
			if(inType.equals("CMD")&& (inCmd.equals("login")))
			{
				String name = inParas.get(0).toString();
				String psd = inParas.get(1).toString();
				if(!name.equalsIgnoreCase(null))
				{	
					//DB inquire
					Statement stmt=null;
					try {
						Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
						String URL="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=ftp";
						Connection conn;
						conn = DriverManager.getConnection(URL,"sa","drean");						 
						stmt =conn.createStatement();
					} catch (ClassNotFoundException e) {
						e.printStackTrace();
					} catch (SQLException e) {
						e.printStackTrace();
					}					
					String sqltxt="select userName,password from userinfo where username='"+name+"' and password='"+psd+"'";
					ResultSet rs;
					//Message msgBack = new Message();
					String ClientSessionId = null; 
					try {
						rs = stmt.executeQuery(sqltxt);
						if(rs.next())
						{
							System.out.println("DataBase Login Ok");
							logFlag=true;
							clientword.command="loginOk";//OK						
							ClientSessionId = sm.generateSessionId();
							System.out.println(ClientSessionId );
							sm.setSession(ClientSessionId,currentpath);
							clientword.paras.add(0,ClientSessionId);//1PARS-SESSIONID
							//2PARS-currentpath+file
							File f1=new File(currentpath);
							for(int i=0;i<f1.list().length;i++)
							{								
								clientword.paras.add(i+1,f1.list()[i]);
							}
							clientword.paras.add(f1.list().length+1,"end");//3PARS-END
							clientword.type = "msg";//TYPE
							
							sockout.writeObject(clientword);
							sockout.flush();
						}else 
						{
							System.out.println("DataBase Login fail");
							clientword.command = "loginFail";//FAIL
							clientword.paras.add(0,"end");//1PARS-END
							clientword.type="msg";//TYPE
							sockout.writeObject(clientword);
							sockout.flush();
						}
					} catch (SQLException e) {
						e.printStackTrace();
					} catch (IOException e1)
					{
						e1.printStackTrace();
					}
				}
			}
			
			//2-login OK,ALL CMD
			while(logFlag)
			{
				if(inType.equals("CMD")&& (!inCmd.equals("login")))
				{	
					if(!sessionId.equals(null))
					{
						sessionId = inParas.get(0).toString();
					}
					currentpath= sm.getPath(sessionId);
				//cd
					 if(inCmd.equals("cd"))
					{
						 prePath = currentpath;							 
						 String currentpath1=currentpath+inParas.get(1).toString()+"/";
							File f=new File(currentpath1);
							if(f.isDirectory()){
								currentpath=currentpath1;
								sm.setSession(sessionId,currentpath);//fresh path in the hashtab
								//1PARS-currentpath+file
								for(int i=0;i<f.list().length;i++)
								{								
									clientword.paras.add(i,currentpath+f.list()[i]);
								}
								clientword.paras.add(f.list().length,"end");//2PARS-END
								clientword.type = "msg";//TYPE
								clientword.command="cd";
							}else
							{
								currentpath=prePath;
								sm.setSession(sessionId,currentpath);//fresh path in the hashtab
								clientword.paras.add(0,"end");//1PARS-END
								clientword.type = "msg";//TYPE	
								clientword.command="cd";
							}
							try {
								sockout.writeObject(clientword);
								sockout.flush();
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
					}
				//cd..
					 else if(inCmd.equals("cd.."))
					 {
						currentpath = prePath;
						sm.setSession(sessionId,currentpath); //fresh path in the hashtable
						File f=new File(currentpath);
						for(int i=0;i<f.list().length;i++)
						{	//1PARS-currentpath+file						
							clientword.paras.add(i,currentpath+f.list()[i]);
						}
						clientword.paras.add(f.list().length,"end");//1PARS-END
						clientword.type = "msg";//TYPE	
						clientword.command="cd..";
						try {
							sockout.writeObject(clientword);
							sockout.flush();
						} catch (IOException e) {
							e.printStackTrace();
						}				
					 }
				 //logout
					else if(inCmd.equals("logout"))
					{		
						sm.getSessions().remove(sessionId);
						//Message msgBack = new Message();
						clientword.command="logoutOk";
						clientword.paras.add(0,"当前用户已经注销!");
						clientword.type="msg";
						try {
							sockout.writeObject(clientword);
							sockout.flush();
						} catch (IOException e) {
							e.printStackTrace();
						}	
					}				
				//exit+close
				else if(inCmd.equals("exit")||inCmd.equals("close"))
				{
					//theThread.currentThread().destroy();					
					try {
						client.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
					return;					
				}
				
			}
				
				//3-login OK,ALL DATA
				else if(inType.equals("DATA"))
			{
					sessionId = inParas.get(0).toString();
					currentpath= sm.getPath(sessionId);
				//get
				if(inCmd.equals("get"))
				{
					file = inParas.get(1).toString();
					clientword.type="DATA";	//TYPE
					clientword.paras.add(0,file);//1PARS-fileName
					File f=new File(currentpath+file);
					clientword.paras.add(1,String.valueOf(f.length()));//2PARS-fileLength
					FileInputStream fw = null;
					byte [] fi=new byte[(int) f.length()];
					try {
						fw = new FileInputStream(f);						
						fw.read(fi);
						fw.close();
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					}catch (IOException e) {
						e.printStackTrace();
					}
					clientword.paras.add(2,fi);//3PARS-fileContent[output Stream]
					clientword.paras.add(3,"data end");//4PARS-dataEND
					clientword.command="get";
					try {
						sockout.writeObject(clientword);
						sockout.flush();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				
				 //put
				else  if(inCmd.equals("put"))
				{
					file = inParas.get(1).toString();
					clientword.type="DATA";
					String uploadFilename = currentpath+file;
					String uploadFileLength = inParas.get(2).toString();
					FileOutputStream fw = null;
					try {
						fw = new FileOutputStream(uploadFilename);
					} catch (FileNotFoundException e1) {
						e1.printStackTrace();
					}
					byte[] content=new byte[Integer.parseInt(uploadFileLength)];
					int i = 0;
					if(!inParas.get(i).toString().equals("data end"))
					{
						content = (byte[]) inParas.get(3);//[receive byte[]]
						i++;
					}
					try {
						fw.write(content);
						fw.close();
						if(fw!=null)
						{
							clientword.command="putOk";
							sockout.writeObject(clientword);
							sockout.flush();
						}
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				}
			}
			}
		}
	}
	
	public static void main(String[] args) 
	{
		threadGroup=new ThreadGroup("Sockets");
		try {
			ServerSocket ss=new ServerSocket(21);
			while(true)
			{
				Socket s=ss.accept();
				new FTPServer(s);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	
		
	}
}

⌨️ 快捷键说明

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