計(jì)算機(jī)網(wǎng)絡(luò)課程設(shè)計(jì) java實(shí)現(xiàn)服務(wù)器端的編程_第1頁
計(jì)算機(jī)網(wǎng)絡(luò)課程設(shè)計(jì) java實(shí)現(xiàn)服務(wù)器端的編程_第2頁
計(jì)算機(jī)網(wǎng)絡(luò)課程設(shè)計(jì) java實(shí)現(xiàn)服務(wù)器端的編程_第3頁
計(jì)算機(jī)網(wǎng)絡(luò)課程設(shè)計(jì) java實(shí)現(xiàn)服務(wù)器端的編程_第4頁
計(jì)算機(jī)網(wǎng)絡(luò)課程設(shè)計(jì) java實(shí)現(xiàn)服務(wù)器端的編程_第5頁
已閱讀5頁,還剩61頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡介

計(jì)算機(jī)網(wǎng)絡(luò)課程設(shè)計(jì)題目:java實(shí)現(xiàn)服務(wù)器端的編程姓名:王.漫漫 學(xué)號:321209010413—指導(dǎo)教師:王蠢一評閱教師: TOC\o"1-5"\h\z\o"CurrentDocument"緒論 3\o"CurrentDocument"2相關(guān)知識 4FTP工作原理 4\o"CurrentDocument"ftp工作模式 6ftp傳輸方式 7ASCII傳輸方式 8\o"CurrentDocument"二進(jìn)制傳輸方式 8\o"CurrentDocument"3需求分析 9\o"CurrentDocument"數(shù)據(jù)需求 9\o"CurrentDocument"功能需求 9\o"CurrentDocument"4詳細(xì)設(shè)計(jì) 9\o"CurrentDocument"5代碼分析 10\o"CurrentDocument"實(shí)現(xiàn)服務(wù)器端功能的代碼: 10\o"CurrentDocument"用戶登錄時(shí)對用戶的用戶,密碼,目錄處理。 12\o"CurrentDocument"主函數(shù) 15\o"CurrentDocument"16\o"CurrentDocument"49\o"CurrentDocument"6運(yùn)行結(jié)果 63緒論1.1緒論隨著計(jì)算機(jī)的普及,網(wǎng)絡(luò)進(jìn)入大眾的家庭,通過網(wǎng)絡(luò)共享數(shù)據(jù)和資源,已不再是什么新鮮的事,盡管Telnet提供了訪問遠(yuǎn)程文件的極好方法,但怎么也比不上使用自己計(jì)算機(jī)中的文件方便。如果用戶想使用其它計(jì)算機(jī)上的文件,最理想的方法就是把它COPY到自己的計(jì)算機(jī)中,以便在本地計(jì)算機(jī)上操作。那么用什么方法去將遠(yuǎn)程計(jì)算機(jī)中的文件獲取過來呢?FTP正是完成這項(xiàng)工作的工具。FTP以它所使用的協(xié)議:文件傳輸協(xié)議(FileTransferProtocol)來命名的。正如其名所示:協(xié)議的任務(wù)是從一臺計(jì)算機(jī)將文件傳送到另一臺計(jì)算機(jī),它與這兩臺計(jì)算機(jī)所處的位置、聯(lián)系的方式、以及使用的操作系統(tǒng)無關(guān)。假設(shè)兩臺計(jì)算機(jī)能與FTP協(xié)議對話,并且能訪HINTERNET,就可以用FTP軟件的命令來傳輸文件。對于不同的操作系統(tǒng)具體操作上可能會有些細(xì)微差別,但是其基本的命令結(jié)構(gòu)是相同的。FTP是個(gè)非常有用的工具,你可以在任意個(gè)可經(jīng)FTP訪問的公共有效的聯(lián)機(jī)數(shù)據(jù)庫或文檔中找到你想要的任何東西。全世界現(xiàn)在已有1000多(96年的數(shù)據(jù))個(gè)FTP文件服務(wù)器對所有INTERNET用戶開使用,用戶可以通過與INTERNET相連的計(jì)算機(jī),把自己需要的文件傳輸過來。FTP采用“客戶機(jī)/服務(wù)器”方式,用戶端要在自己的本地計(jì)算機(jī)上安裝FTP客戶程序。FTP客戶程序有字符界和圖形界面(如CuteFTP)兩種。2相關(guān)知識FTP工作原理FTP(FileTransferProtocol),是文件傳輸協(xié)議的簡稱。用于Internet上的控制文件的雙向傳輸。同時(shí),它也是一個(gè)應(yīng)用程序。用戶可以通過它把自己機(jī)器與世界各地所有運(yùn)FTP協(xié)議的服務(wù)器相連,訪問服務(wù)器上的資源和信息。FTP協(xié)議在TCP/IP協(xié)議棧中的位置如表I:HTTPFTPTELNSMTPDNSTFTPNMP應(yīng)用層TCPUDP傳輸層IP互聯(lián)網(wǎng)絡(luò)層X25ISDNLANWLANFDDIATM網(wǎng)絡(luò)接口層當(dāng)啟動FTP從遠(yuǎn)程計(jì)算機(jī)拷貝文件時(shí),事實(shí)上啟動了兩個(gè)程序:一個(gè)本地機(jī)器上的FTP客戶端程序,它向FTP服務(wù)器提出拷貝文件的請求。另一個(gè)是啟動在遠(yuǎn)程計(jì)算機(jī)的上的FTP服務(wù)器程序,它響應(yīng)請求把你指定的文件傳送到你的計(jì)算機(jī)中。FTP采用“客戶端/服務(wù)器”方式,用戶要在自己的本地計(jì)算機(jī)上安裝FTP客戶端程序。從根本上說,F(xiàn)TP協(xié)議就是在網(wǎng)絡(luò)中各種不同的計(jì)算機(jī)之間按照TCP/IP協(xié)議來傳輸文件。FTP協(xié)議采用客戶端/服務(wù)器(Client/Sever)模式,由FTP客戶端程序和FTP服務(wù)器端程序組成。使用時(shí),先啟動FTP客戶端程序與遠(yuǎn)程主機(jī)建立連接,然后向遠(yuǎn)程主機(jī)發(fā)出傳輸命令,遠(yuǎn)程主機(jī)在收到命令后就給予響應(yīng),并執(zhí)行正確的命令。但是FTP有一個(gè)根本的限制,那就是,如果用戶在某個(gè)主機(jī)上沒有注冊獲得授權(quán),即沒有用戶名和口令,就不能與該主機(jī)進(jìn)行文件傳輸。但匿名FTP服務(wù)器除外,它能夠使用戶與遠(yuǎn)程主機(jī)建立連接并以匿名身份從遠(yuǎn)程主機(jī)上拷貝文件,而不必是該遠(yuǎn)程主機(jī)的注冊用戶。用戶使用特殊的用戶名“Anonymous”或“guest”就可有限制地訪問遠(yuǎn)程主機(jī)上公開的文件。現(xiàn)在許多系統(tǒng)要求用戶將Email地址作為口令,以便更好地對訪問者進(jìn)行跟綜。出于安全的目的,大部分匿名FTP主機(jī)一般只允許遠(yuǎn)程用戶下載文件,而不允許上載文件。也就是說,用戶只能從匿名FTP主機(jī)拷貝其需要的文件而不能把文件拷貝到匿名FTP主機(jī)。另外,匿名FTP主機(jī)還采用了其他一些保護(hù)措施以保護(hù)自己的文件不至于被用戶修改和刪除,并防止計(jì)算機(jī)病毒的侵入。匿名FTP一直是Internet上獲取信息資源的最主要方式,在Internet成千上萬的匿名FTP主機(jī)中存儲著無以計(jì)數(shù)的文件,這些文件包含了各種各樣的信息、數(shù)據(jù)和軟件。人們只要知道特定信息資源的主機(jī)地址,就可以用匿名FTP登陸。ftp工作模式FTP采用C/S(客戶端/服務(wù)器)模式進(jìn)行通信,但與其他的C/S模式網(wǎng)絡(luò)通信協(xié)議又有一個(gè)很大的區(qū)別。通常在進(jìn)行HTTP通信或是TELNET通信的時(shí)候,只需要一個(gè)端口進(jìn)行通信。即客戶端只需要連接一個(gè)端口進(jìn)行數(shù)據(jù)通信。如TELNET的默認(rèn)端口是23,用戶從頭到尾都只需使用這個(gè)端口。但是FTP通信除了有一個(gè)默認(rèn)端口21之外,還需要其他的端口。其中默認(rèn)端口(21)主要進(jìn)行控制連接,進(jìn)行命令協(xié)議和服務(wù)器端的響應(yīng)碼的傳輸;另外一個(gè)非標(biāo)準(zhǔn)端口主要進(jìn)行數(shù)據(jù)傳遞,如文件的上載、下載等。至于非標(biāo)準(zhǔn)端口的產(chǎn)生則要根據(jù)用戶選擇的連接模式而定:如果客戶選擇的是主動模式(PORT),則需要用戶端提供給服務(wù)器一個(gè)IP地址和一個(gè)非標(biāo)準(zhǔn)端口;而如果用戶采用被動模式(PASV),則服務(wù)器端需要提供給客戶端一個(gè)IP地址和一個(gè)非標(biāo)準(zhǔn)端口。下表是幾個(gè)著名的TCP端口號:表2TCP端口號TCP端口號關(guān)鍵字描述20FTP-DATA文件傳輸協(xié)議數(shù)據(jù)21FTP文件傳輸協(xié)議控制23TELENET遠(yuǎn)程登錄協(xié)議25SMTP簡單郵件傳輸協(xié)議53DOMAIN域名服務(wù)器80HTTP超文本傳輸協(xié)議110POP3郵局協(xié)議119NNTP新聞傳送協(xié)議FTP中字節(jié)大小有兩個(gè):邏輯字節(jié)大小和用于傳輸?shù)淖止?jié)大小。后者通常是8位,而前者可不一定是多少了。傳輸字節(jié)不必等于邏輯字節(jié)大小,也不必對數(shù)據(jù)結(jié)構(gòu)進(jìn)行解釋??刂七B接是建立在USER-PIT和SERVER-PI之間用于交換命令與應(yīng)答的通信鏈路。數(shù)據(jù)連接是傳輸數(shù)據(jù)的全雙工連接,傳輸數(shù)據(jù)可以發(fā)生在服務(wù)器DTP和用戶DTP之間也可以發(fā)生在兩個(gè)服務(wù)器DTP之間,F(xiàn)TP可以傳輸非連續(xù)的文件,這些文件的一部分稱為頁。服務(wù)器DTP代表一種傳輸過程,它通常處于“主動”狀態(tài),它和偵聽端口建立數(shù)據(jù)連接,它還可以為傳輸和存儲設(shè)置參數(shù),并根據(jù)PI的指令傳輸數(shù)據(jù)。當(dāng)然,DTP也可以轉(zhuǎn)入“被動”狀態(tài)。服務(wù)器FTP進(jìn)程,它是和用戶FTP進(jìn)程一起工作的,它由PI和DTP組成。在開始階段,標(biāo)準(zhǔn)FTP命令由用戶PI產(chǎn)生并通過控制連接傳送到服務(wù)器進(jìn)程。服務(wù)器PI向用戶PI返回標(biāo)準(zhǔn)應(yīng)答。FTP命令指定數(shù)據(jù)連接參數(shù)和文件系統(tǒng)操作。用戶DTP在特定數(shù)據(jù)端口偵聽,服務(wù)器開始數(shù)據(jù)連接并以指定的參數(shù)開始數(shù)據(jù)傳輸。數(shù)據(jù)端口不必在開始FTP命令的機(jī)器上,但用戶或用戶FTP進(jìn)程必須確定它在指定的數(shù)據(jù)端口上偵聽.這個(gè)數(shù)據(jù)連接是全雙工的。ftp傳輸方式FTP協(xié)議的任務(wù)是從一臺計(jì)算機(jī)將文件傳送到另一臺計(jì)算機(jī),它與這兩臺計(jì)算機(jī)所處的位置、聯(lián)接的方式、甚至是是否使用相同的操作系統(tǒng)無關(guān)。假設(shè)兩臺計(jì)算機(jī)通過ftp協(xié)議對話,并且能訪問Internet,你可以用ftp命令來傳輸文件。每種操作系統(tǒng)使用上有某一些細(xì)微差別,但是每種協(xié)議基本的命令結(jié)構(gòu)是相同的。FTP的傳輸有兩種方式:ASCII傳輸模式和二進(jìn)制數(shù)據(jù)傳輸模式。ASCII傳輸方式假定用戶正在拷貝的文件包含的簡單ASCII碼文本,如果在遠(yuǎn)程機(jī)器上運(yùn)行的不是UNIX,當(dāng)文件傳輸時(shí)ftp通常會自動地調(diào)整文件的內(nèi)容以便于把文件解釋成另外那臺計(jì)算機(jī)存儲文本文件的格式。但是常常有這樣的情況,用戶正在傳輸?shù)奈募牟皇俏谋疚募鼈兛赡苁浅绦?,?shù)據(jù)庫,字處理文件或者壓縮文件(盡管字處理文件包含的大部分是文本,其中也包含有指示頁尺寸,字庫等信息的非打印字符)。在拷貝任何非文本文件之前,用binary命令告訴ftp逐字拷貝,不要對這些文件進(jìn)行處理。二進(jìn)制傳輸方式在二進(jìn)制傳輸中,保存文件的位序,以便原始和拷貝的是逐位一一對應(yīng)的。即使目的地機(jī)器上包含位序列的文件是沒意義的。例如,macintosh以二進(jìn)制方式傳送可執(zhí)行文件到Windows系統(tǒng),在對方系統(tǒng)上,此文件不能執(zhí)行。如果你在ASCII方式下傳輸二進(jìn)制文件,即使不需要也仍會轉(zhuǎn)譯。這會使傳輸稍微變慢,也會損壞數(shù)據(jù),使文件變得不能用。3需求分析設(shè)計(jì)和實(shí)現(xiàn)FTP服務(wù)器,主要是遵從FTP協(xié)議標(biāo)準(zhǔn)實(shí)現(xiàn)FTP服務(wù)器;允許現(xiàn)有標(biāo)準(zhǔn)的FTP客戶端與它互連互通;支持上傳和下載文件。數(shù)據(jù)需求由于匿名FTP的功能比非匿名FTP有很大的限制,所以為了完成上傳下載文件功能,需要設(shè)計(jì)非匿名FTP,即需要通過賬號和密碼才能訪問此服務(wù)器,則服務(wù)器需要有創(chuàng)建賬號功能,并保存賬號信息,這需要建立對應(yīng)的數(shù)據(jù)結(jié)構(gòu)表。功能需求FTP服務(wù)器要有可供管理的主界面,并可以通過這個(gè)界面來添加刪除賬號,設(shè)置路徑,查詢信息,并根據(jù)需要啟動和關(guān)閉服務(wù)。在起內(nèi)部需要支持上傳下載文件功能。4詳細(xì)設(shè)計(jì)

圖3-1客戶端連接流程圖。5代碼分析實(shí)現(xiàn)服務(wù)器端功能的代碼:publicclassFtpServerprivateSocketsocketclient;privateintcounter;publicstaticStringinitDir;publicstaticArrayListusers=newArrayList();publicstaticArrayListuserslnfo=newArrayList();publicFtpServer()(FtpConsolefc=newFtpConsole();fc.start();loadUsersInfo();intcounter=1;inti=0;try(〃監(jiān)聽21號端口ServerSockets=newServerSocket(21);創(chuàng)建服務(wù)器端的socket并設(shè)置監(jiān)聽端口21for(;;){〃接受客戶端請求Socketincoming=s.accept();BufferedReaderin=newBufferedReader(newInputStreamReader(incoming.getInputStream()));PrintWriterout=newPrintWriter(incoming.getOutputStream(),true);out.println("220Servicereadyfornewuser"+counter);〃創(chuàng)建服務(wù)線程FtpHandlerh=newFtpHandler(incoming,i);h.start();users.add(h);counter++;i++;})catch(Exceptione)(e.printStackTrace();}}//FtpServer()end用戶登錄時(shí)對用戶的用戶,密碼,目錄處理。publicvoidloadUsersInfo()Strings=getClass().getResource("user.cfg").toString();s=s.substring(6,s.length());intpl=0;intp2=0;if(newFile(s).exists())(try{BufferedReaderfin=newBufferedReader(newInputStreamReader(newFilelnputStream(s)));Stringline;Stringfield;inti=0;while((line=fin.readLine())!=null)(UserinfotempUserlnfo=newUserlnfo();pl=0;p2=0;if(line.startsWith("#"))continue;while((p2=line.indexOf('T',p1))!=-1)(field=line.substring(p1,p2);p2=p2+1;pl=p2;switch(i)(case0:tempUserlnfo.user=field;//System.out.println(tempUserlnfo.user);break;tempUserlnfo.password=field;//System.out.println(tempUserInfo.password);break;tempUserlnfo.workDir=field;//System.out.println(tempUserlnfo.workDir);break;i++;}//while((p2=line.indexOf('T',p1))!=-1)endusersInfo.add(tempUserlnfo);}//while((line=fin.readLine())!=null)endfin.close();Icatch(Exceptione)(e.printStackTrace();)}//if(newFile(s).exists())end}//loadUsersInfo()end主函數(shù)publicstaticvoidmain(String[]args){if(args.length!=0)initDir=args[0];elseinitDir="c:/";)FtpServerftpServer=newFtpServer();}//mainendclassFtpHandlerextendsThread(Socketcsocket;用于控制的套接字Socketdsocket;用于傳輸?shù)奶捉幼謎ntid;Stringcmd=嗎存放指令空格前Stringparam=存放當(dāng)前指令后的參數(shù)Stringuser;StringremoteHost="客戶IPintremotePort=0;客戶Tcp端口號Stringdir=FtpServer.initDir;當(dāng)前目錄Stringrootdir="c:/";//默認(rèn)根目錄,在checkPASS中設(shè)置intstate=0;Stringreply;PrintWriterout;inttype=0;Stringrequestfile=booleanisrest=false;intparseInput(Strings)(intp=0;inti=-1;p=s.indexOf("");if(p==-1)cmd=s;elsecmd=s.substring(0,p);if(p>=s.length()IIp==-l)param=elseparam=s.substring(p+1,s.length());cmd=cmd.toUpperCase();if(cmd.equals("USER"))i=1;if(cmd.equals("PASS"))i=2;if(cmd.equals("ACCT"))i=3;if(cmd.equals("CDUP"))i=4;if(cmd.equals("SMNT"))i=5;if(cmd.equals("CWD"))i=6;if(cmd.equals("QUIT"))i=7;if(cmd.equals("REIN"))i=8;if(cmd.equals("PORT"))if(cmd.equals("PASV"))i=10;if(cmd.equals("TYPE"))i=11;if(cmd.equals("STRU"))i=12;if(cmd.equals("MODE"))i=13;if(cmd.equals("RETR"))i=14;if(cmd.equals("STOR"))i=15;if(cmd.equals("STOU"))i=16;if(cmd.equals("APPE"))i=17;if(cmd.equals("ALLO"))i=18;if(cmd.equals("REST"))i=19;if(cmd.equals("RNFR"))if(cmd.equals("RNTO"))i=21;if(cmd.equals("ABOR"))i=22;if(cmd.equals("DELE"))i=23;if(cmd.equals("RMD"))i=24;if(cmd.equals("XMKD"))i=25;if(cmd.equals("MKD"))i=25;if(cmd.equals("PWD"))i=26;if(cmd.equals("LIST"))i=27;if(cmd.equals("NLST"))i=28;if(cmd.equals("SITE"))i=29;if(cmd.equals("SYST"))if(cmd.equals("HELP"))=31;if(cmd.equals("NOOP"))i=32;if(cmd.equals("XPWD"))i=33;returni;}//parseInput()endintvalidatePath(Strings)(Filef=newFile(s);if(f.exists()&&!f.isDirectory())(Stringsi=s.toLowerCase();Strings2=rootdir.toLowerCase();if(sl.startsWith(s2))return1;elsereturn0;f=newFile(addTail(dir)+s);if(f.exists()&&!f.isDirectory())Stringsi=(addTail(dir)+s).toLowerCase();Strings2=rootdir.toLowerCase();if(sl.startsWith(s2))return2;elsereturn0;}return0;}//validatePath()endbooleancheckPASS(Strings)(for(inti=0;i<FtpServer.usersInfo.size();i++)(if(((UserInfo)FtpServer.usersInfo.get(i)).user.equals(user)&&((UserInfo)FtpServer.usersInfo.get(i)).password.equals(s)){rootdir=((UserInfo)FtpServer.usersInfo.get(i)).workDir;dir=((UserInfo)FtpServer.usersInfo.get(i)).workDir;returntrue;returnfalse;}//checkPASS()endbooleancommandUSER(){if(cmd.equals("USER")){reply="331Usernameokay,needpassword";user=param;state=FtpState.FS_WAIT_PASS;returnfalse;)else(reply="501Syntaxerrorinparametersorarguments";returntrue;}//commandUser()endbooleancommandPASS()if(cmd.equals("PASS"))(if(checkPASS(param))(reply="230Userloggedin,proceed";state=FtpState.FS_LOGIN;System.out.println("Message:user"+user+"Form"+remoteHost+"Login");System.out.print("->");returnfalse;)else{reply="530Notloggedin";returntrue;))elsereply="501Syntaxerrorinparametersorarguments";returntrue;}//commandPass()endvoiderrCMD(){reply="500Syntaxerror,commandunrecognized";)booleancommandCDUP(){dir=FtpServer.initDir;Filef=newFile(dir);if(f.getParent()!=null&&(!dir.equals(rootdir)))(dir=f.getParent();reply="200Commandokay";)elsereply="550Currentdirectoryhasnoparent";returnfalse;}//commandCDUP()endbooleancommandCWD(){Filef=newFile(param);Strings=Stringsi=if(dir.endsWith("/"))s=dir;elses=dir+V";Filefl=newFile(s+param);if(f.isDirectory()&&f.exists())(if(param.equals("..")IIparam.equals("..\\"))if(pareToIgnoreCase(rootdir)==0)reply="550Thedirectorydoesnotexists";//returnfalse;)else{si=newFile(dir).getParent();if(sl!=null){dir=si;reply="250Requestedfileactionokay,directorychangeto"+dir;}elsereply="550Thedirectorydoesnotexists";)Ielseif(param.equals(".")IIparam.equals(".\\"))(}elsedir=param;reply="250Requestedfileactionokay,directorychangeto"+dir;elseif(f1.isDirectory()&&fl.exists())(dir=s+param;reply="250Requestedfileactionokay,directorychangeto"+dir;)elsereply="501Syntaxerrorinparametersorarguments";returnfalse;}//commandCDW()endbooleancommandQUIT()(reply="221Serviceclosingcontrolconnection";returntrue;}//commandQuit()endbooleancommandPORT()intpl=0;intp2=0;int[]a=newint[6];inti=0;try(while((p2=param.indexOf(",",p1))!=-1)(a[i]=Integer.parselnt(param.substring(p1,p2));p2=p2+1;pl=p2;i++;)a[i]=Integer.parselnt(param.substring(pl,param.length()));}catch(NumberFormatExceptione)(reply="501Syntaxerrorinparametersorarguments";returnfalse;remoteHost=a[0]+"."+a[l]4-"."+a[2]+"."4-a[3];remotePort=a[4]*256+a[5];reply="200Commandokay";returnfalse;}//commandPort()endbooleancommandLIST()(try(dsocket=newSocket(remoteHost,remotePort,InetAddress.getLocalHost(),20);PrintWriterdout=newPrintWriter(dsocket.getOutputStream(),true);if(param.equals("")IIparam.equals("LIST")){out.println("150OpeningASCIImodedataconnectionfor/bin/ls.");Filef=newFile(dir);String[]dirStructure=f.list();StringfileType;for(inti=0;i<dirStructure.length;i++)if(dirStructure[i].indexOf(".")!=-1)(fileType=)else(fileType="d)dout.println(fileType+dirStructure[i]);))dout.close();dsocket.close();reply="226Transfercomplete!";}catch(Exceptione)(e.printStackTrace();reply="451Requestedactionaborted:localerrorin , H.processing;returnfalse;returnfalse;}//commandLIST()endbooleancommandTYPE()(if(param.equals("a"))(type=FtpState.FTYPE_ASCII;reply="200CommandokayChangetoASCIImode";)elseif(param.equals("i"))(type=FtpState.FTYPE_IMAGE;reply="200CommandokayChangetoBINARYmode";)elsereply="504Commandnotimplementedforthatparameter";returnfalse;}//commandTYPE()endbooleancommandRETR()(requestfile=param;Filef=newFile(requestfile);if(!f.exists())(f=newFile(addTail(dir)+param);if(!f.exists()){reply="550Filenotfound";returnfalse;)requestfile=addTail(dir)+param;)if(isrest)elseif(type==FtpState.FTYPE_IMAGE)try{out.println("150OpeningBinarymodedataconnectionfor"+requestfile);dsocket=newSocket(remoteHost,remotePort,InetAddress.getLocalHost(),20);BufferedlnputStreamfin=newBufferedInputStream(newFilelnputStream(requestfile));PrintStreamdout=newPrintStream(dsocket.getOutputStream(),true);byte[]buf=newbyte[1024];int1=0;while((l=fin.read(buf,0,1024))!=-l){dout.write(buf,0,1);)fin.close();dout.close();dsocket.close();reply="226Transfercomplete!";catch(Exceptione){e.printStackTrace();reply="451Requestedactionaborted:localerrorinprocessing";returnfalse;))if(type==FtpState.FTYPE_ASCII)out.println("150OpeningASCIImodedataconnectionfor"+requestfile);dsocket=newSocket(remoteHost,remotePort,InetAddress.getLocalHost(),20);BufferedReaderfin=newBufferedReader(newFileReader(requestfile));PrintWriterdout=newPrintWriter(dsocket.getOutputStream(),true);Strings;while((s=fin.readLine())!=null)(dout.println(s);)fin.close();dout.close();dsocket.close();reply="226Transfercomplete!";catch(Exceptione)(e.printstackTrace();reply="451Requestedactionaborted:localerrorinprocessing;returnfalse;returnfalse;}//commandRETR()endbooleancommandSTOR()(if(param.equals(""))(reply="501Syntaxerrorinparametersorarguments";returnfalse;)requestfile=addTail(dir)+param;if(type==FtpState.FTYPEJMAGE)(try{out.println("150OpeningBinarymodedataconnectionfor"+requestfile);dsocket=newSocket(remoteHost,remotePort,InetAddress.getLocalHost(),20);BufferedOutputStreamfout=newBufferedOutputStream(newFileOutputStream(requestfile));BufferedlnputStreamdin=newBufferedInputStream(dsocket.getInputStream());byte[]buf=newbyte[1024];int1=0;while((l=din.read(buf,0,1024))!=-l){fout.write(buf,0,l);}//while()din.close();fout.close();dsocket.close();reply="226Transfercomplete!";)catch(Exceptione)(e.printStackTrace();reply="451Requestedactionaborted:localerrorinprocessing";returnfalse;if(type==FtpState.FTYPE_ASCII)tryout.println("150OpeningASCIImodedataconnectionfor"+requestfile);dsocket=newSocket(remoteHost,remotePort,InetAddress.getLocalHost(),20);PrintWriterfout=newPrintWriter(newFileOutputStream(requestfile));BufferedReaderdin=newBufferedReader(newInputStreamReader(dsocket.getInputStream()));Stringline;while((line=din.readLine())!=null){fout.println(line);)din.close();fout.close();dsocket.close();reply="226Transfercomplete!";catch(Exceptione)e.printStackTrace();reply="451Requestedactionaborted:localerrorin, Itprocessing;returnfalse;))returnfalse;}//commandSTOR()endbooleancommandPWD()(reply="257"+dir+"iscurrentdirectory.";returnfalse;}//commandPWD()endbooleancommandNOOP()(reply="200OK.";returnfalse;}//commandNOOP()endbooleancommandABOR()trydsocket.close();catch(Exceptione)(e.printStackTrace();reply="451Requestedactionaborted:localerrorinprocessing";returnfalse;)reply="421Servicenotavailable,closingcontrolconnection";returnfalse;}//commandABOR()endbooleancommandDELE()(inti=validatePath(param);if(i==0)reply="550Requestactionnottaken";returnfalse;if(i==1)(Filef=newFile(param);f.delete();)if(i==2){Filef=newFile(addTail(dir)+param);f.delete();)reply="250Requestfileactionok,complete";returnfalse;}//commandDELE()endbooleancommandMKD()(Stringsi=param.toLowerCase();Strings2=rootdir.toLowerCase();if(s1.startsWith(s2))Filef=newFile(param);if(f.exists()){reply="550Requestactionnottaken";returnfalse;)else{f.mkdirs();reply="250Requestfileactionok,complete";))else(Filef=newFile(addTail(dir)+param);if(f.exists()){reply="550Requestactionnottaken";returnfalse;elsef.mkdirs();reply="250Requestfileactionok,complete";returnfalse;}//commandMKD()endStringaddTail(Strings)(if(!s.endsWith('7"))s=s+V";returns;)publicFtpHandler(Sockets,inti)(csocket=s;id=i;publicvoidrun()Stringstr=intparseResult;BufferedReaderin=newBufferedReader(newInputStreamReader(csocket.getInputStream()));out=newPrintWriter(csocket.getOutputStream(),true);state=FtpState.FS_WAIT_LOGIN;booleanfinished=false;while(Jfinished){str=in.readLine();if(str==null)finished=true;elseparseResult=parselnput(str);System.out.println("Command:"+cmd+"Parameter:"+param);System.out.print("->");switch(state)(caseFtpState.FS_WAIT_LOGIN:finished=commandUSER();break;caseFtpState.FS_WAIT_PASS:finished=commandPASS();break;caseFtpState.FS_LOGIN:(switch(parseResult){case-1:errCMD();break;case4:finished=commandCDUP();break;finished=commandCWD();break;finished=commandQUIT();break;case9:finished=commandPORT();break;case27:finished=commandLIST();break;case11:finished=commandTYPE();break;finished=commandRETR();break;finished=commandSTOR();break;case26:finished=commandPWD();break;case32:finished=commandNOOP();break;finished=commandABOR();break;finished=commandDELE();break;case25:finished=commandMKD();break;}//switch(parseResult)end}//caseFtpState.FS_LOGIN:endbreak;}//switch(state)end}//elseout.println(reply);}//whilecsocket.close();}//trycatch(Exceptione)(e.printStackTrace();))5.5classFtpConsoleextendsThread(BufferedReadercin;StringconCmd;StringconParam;intconsoleQUIT(){System.exit(O);return0;}//consoleQUIT()endbooleanconsoleLISTUSER()(System.out.println("username\t\tworkdirectory");for(inti=0;i<FtpServer.usersInfo.size();i++){System.out.println(((UserInfo)FtpServer.usersInfo.get(i)).user+"\t\t\t"+((UserInfo)FtpServer.usersInfo.get(i)).workDir);)returnfalse;}Z/consoleLISTUSER()endbooleanconsoleLIST()(inti=0;for(i=0;i<FtpServer.users.size();i++){System.out.println((i+1)+":"+((FtpHandler)(FtpServer.users.get(iFrom))).userFrom+((FtpHandler)(FtpServer.users.get(i))).csocket.getInetAddress().toString());returnfalse;}//consoleLIST()endbooleanvalidateUserName(Strings){for(inti=0;i<FtpServer.usersInfo.size();i++){if(((UserInfo)FtpServer.usersInfo.get(i)).user.equals(s))returnfalse;)returntrue;}//validateUserName()endbooleanconsoleADDUSER()(System.out.print("pleaseenterusername:");try

cmnewBufferedReader(newcmnewBufferedReader(newInputStreamReader(System.in));UserinfotempUserlnfo=newUserlnfo();Stringline=cin.readLine();if(line!="")(if(!validateUserName(line))(System.out.println("user"+line+"alreadyexists!");returnfalse;elseSystem.out.println("usernamecannotbenull!");returnfalse;)tempUserlnfo.user=line;System.out.print("enterpasswordline=cin.readLine();if(line!="")tempUserlnfo.password=line;else(System.out.println("passwordcannotbenull!");returnfalse;)System.out.print("entertheinitialdirectory:");line=cin.readLine();if(line!="")(Filef=newFile(line);if(!f.exists())f.mkdirs();tempUserlnfo.workDir=line;)else(System.out.println("thedirectorycannotbenull!");returnfalse;)FtpServer.usersInfo.add(tempUserlnfo);saveUserInfo();catch(Exceptione){e.printStackTrace();returnfalse;)returnfalse;}//consoleADDUSER()endvoidsaveUserInfo()(Strings=try(BufferedWriterfout=newBufferedWriter(newOutputStreamWriter(newFileOutputStream("user.cfg")));for(inti=0;i<FtpServer.usersInfo.size();i++)(s =((UserInfo)FtpServer.usersInfo.get(i)).user4-'T'+((UserInfo)FtpServer.usersInfo.get(i)).password4-'T'+((UserInfo)FtpServer.usersInfo.get(i)).workDir+'T';fout.write(s);fout.newLine();fout.close();)catch(Exceptione)(e.printStackTrace();)}//saveUserInfo()endbooleanconsoleDELUSER()(Strings=//System.out.println(conParam);if(conParam.equals(""))(System.out.println("usage:deluserusername");returnfalse;for(inti=0;i<FtpServer.usersInfo.size();i++)s=((UserInfo)FtpServer.usersInfo.get(i)).user;if(s.equals(conParam))(System.out.println("User"+conParam+"deleted");FtpServer.usersInfo.remove(i);saveUserInfo();returnfalse;))System.out.println("User"+conParam+"notexists");returnfalse;}//consoleDELUSER()endbooleanconsoleHELP()(if(conParam.equals(""))(System.out.println("adduser:addnewuser");System.out.println("deluser<username>:deleteauser");System.out.println("quit:quit");System.out.println("list:listalluserconnecttoserver");System.out.println("listuser:listallaccountofthisserver");System.out.println("help:showthishelp");)elseif(conParam.equals("adduser"))System.out.println("adduser:addnewuser");elseif(conParam.equals("deluser"))System.out.println("deluser<username>:deleteauser");elseif(conParam.equals("quit"))System.out.println("quit:quit");elseif(conParam.equals("list"))System.out.println("list:listalluserconnecttoserver");elseif(conParam.equals("listuser"))System.out.println("listuser:listallaccountofthisserver");elseif(conParam.equals("help"))System.out.println("help:showthishelp");elsereturnfalse;returnfalse;}//consoleHELP()endbooleanconsoleERR(){System.out.println("badcommand!");returnfalse;}//consoleERR()endpublicFtpConsole()(System.out.println("ftpserverstarted!");cin = new BufferedReader(newInputStreamReader(System.in));)publicvoidrun()booleanok=false;Stringinput=while(!ok){System.out.print("->");try(input=cin.readLine();)catch(Exceptione)(e.printStackTrace();)switch(parselnput(input))(case1:consoleQUIT();break;case8:ok=consoleLISTUSER();break;case0:ok=consoleLIST();break;ok=consoleADDUSER();break;ok=consoleDELUSER();break;case7:ok=consoleHELP();break;case-1:ok=consoleERR();break;)}//whileend//}//run()endintparseInput(Strings)StringupperCmd;intp=0;conCmd=conParam=p=s.indexOf("");if(p==-1)conCmd=s;elseconCmd=s.substring(O,p);if(p>=s.length()IIp==

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

最新文檔

評論

0/150

提交評論