課件課后練習(xí)代碼-經(jīng)典案例_第1頁(yè)
課件課后練習(xí)代碼-經(jīng)典案例_第2頁(yè)
課件課后練習(xí)代碼-經(jīng)典案例_第3頁(yè)
課件課后練習(xí)代碼-經(jīng)典案例_第4頁(yè)
課件課后練習(xí)代碼-經(jīng)典案例_第5頁(yè)
已閱讀5頁(yè),還剩55頁(yè)未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

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

文檔簡(jiǎn)介

JavaSE02DMS4.0——DMSRequest和DMSResponse的設(shè)計(jì)和編DMS4.0——發(fā)送功能的設(shè)計(jì)和DMS4.0——接收功能的設(shè)計(jì)和DMS4.0— 功能的設(shè)計(jì)和編寫DMS4.0——服務(wù)端界面的設(shè)計(jì)和創(chuàng)建網(wǎng)絡(luò)通信協(xié)議類Protocol,該類設(shè)計(jì)成抽象類。實(shí)現(xiàn)以下面的功能@param<E>publicclassProtocol<E>privateMap<String,String>head=newHashMap<String,protectedEdata;publicEgetData()return}publicvoidsetData(E{this.data=}protectedvoidsetHead(Stringname,String{head.put(name,}public voidsendTo(Socketsocket)throws**@paramsocket接收來源*@throwspublic voidreceiveFrom(Socketsocket)throws}protectedStringgetHead(Stringname)return}@paramsocket發(fā)送目標(biāo)@throwsprotectedStringgetHead(Stringname)return}@paramsocket發(fā)送目標(biāo)@throws@param<E>publicclassProtocol<E>privateMap<String,String>head=newHashMap<String,protectedEdata;publicEgetData() return publicvoidsetData(Edata)this.data= protectedvoidsetHead(Stringname,Stringvalue)head.put(name, protectedStringgetHead(Stringname)return **@paramsocket發(fā)送目標(biāo)*@throwspublic voidsendTo(Socketsocket)throws**@paramsocket接收來源*@throwspublic voidreceiveFrom(Socketsocket)throws}*端發(fā)送的無連接請(qǐng)求協(xié)議,繼承了ProtocolpublicclassDMSRequestextendsProtocol<List<LogRec>>//協(xié)議中的頭屬性名,表示發(fā)送時(shí)間的privatestaticfinalStringREQUEST_HEAD_SENDTIME=端服務(wù)器的privatestaticfinalStringREQUEST_HEAD_CLIENT_NAME= //協(xié)議中的頭屬性名,表示記錄數(shù)量的privatestaticfinalString UM=" publicDMSRequest(){ publicDMSRequest(List<LogRec>recList)this(recList,null); **@paramrecList*@paramclientName發(fā)送消 端publicDMSRequest(List<LogRec>recList,StringclientName) **@param umpublic um) UM, *@return日志記錄數(shù)量public um()return **@paramtimeMillispublicvoid dTime(longtimeMillis)setHead(REQUEST_HEAD_SENDTIME, *@return發(fā)送時(shí)間publiclong dTime()return *設(shè)置協(xié)議頭屬性,發(fā)送端*@paramclientName發(fā)送端publicvoidsetClientName(StringclientName)setHead(REQUEST_HEAD_CLIENT_NAME, 協(xié)議頭屬性,發(fā)送端*@return發(fā)送端publicStringgetClientName()return **@paramsccket發(fā)送目標(biāo)publicvoidsendTo(Socketsocket)throwsExceptionOutputStreamos=PrintWriterps=newps.println("DMS for(inti=0;i<data.size();i++) **@paramsccket接收來源publicvoidreceiveFrom(Socketsocket)throws{InputStreamis=BufferedReaderbr=newBufferedReader(newStringdmsReq=StringclientName=StringsendTime= um=br.readLine();setHead(REQUEST_HEAD_CLIENT_NAME,setHead(REQUEST_HEAD_SENDTIME, data=newfor(inti=0;i um();i++)Stringline=LogReclogRec=new publicclassDMSResponseextendsProtocol//200publicstaticfinalintRESPONSE_CODE_OK=//500publicstaticfinalintRESPONSE_CODE_ERROR=privatestaticfinalStringRESPONSE_HEAD_CODE="CODE"; publicDMSResponse() **@paramcode服務(wù)器反饋狀態(tài)碼,200=OK,publicDMSResponse(intcode) **@paramcodepublicvoidsetResponseCode(intcode)setHead(RESPONSE_HEAD_CODE, *@returnpublicgetResponseCode()return}**@paramsccket發(fā)送目標(biāo)publicvoidsendTo(Socketsocket)throwsExceptionOutputStreamos=PrintWriterpw=newpw.println("DMS}@paramsccket接收來源publicvoidreceiveFrom(Socketsocket)throwsInputStreamis=socket.getInputStream();BufferedReaderbr=newBufferedReader(newStringresponse=br.readLine();StringresponseCode=br.readLine();setHead(RESPONSE_HEAD_CODE,responseCode);}Exception}在DMS4.0項(xiàng)目中端需要向服務(wù)器端發(fā)送日志數(shù)據(jù),現(xiàn)需要設(shè)計(jì)和編寫發(fā)送日志數(shù)據(jù)的privatevoidinitSocket()if(host!=null&&port!=null){trysocket=newSocket(host,}catch(Exception{thrownewRuntimeException("服務(wù)器連接錯(cuò)誤",}}elsethrownewRuntimeException(}}publicbooleansent()tryDMSRequestrequest=newDMSRequest(matched,DMSResponseresponse=newDMSResponse();intrespCode=if(respCode=={return}return}catch(Exception{;returnfalse;} * 端程序,實(shí)現(xiàn) *publicclass{privateLogDataSource/**全部匹配的成對(duì)的Log記錄privateList<LogRec>matched=new/**已經(jīng)登錄沒有登出的log記錄,也就是不配對(duì) 記錄privateList<LogData>loginLogs=new/**定時(shí)器,用于定時(shí)獲取日志數(shù)據(jù)源數(shù)據(jù).privateTimer/**匹配成功的登錄日志對(duì)privatestatic MITTED_REC= /**已經(jīng)登錄,沒有登出的日志信息privatestaticStringUNMATCHED_LOG_FILE="unmatchedlog.txt";privatePropertiesprivateStringprivateStringprivateintprivateintprivateSocketprivate privateFileprivateInfo/**計(jì)費(fèi)登錄的計(jì)算機(jī)IP,從配置文 privateStringserverHost; privateStringclientName;publicDMSClient()logDataSource=newtimer=newmittedRecFile=new unmatchedLogFile=newclientInfo=newDMSClientFrameclientFrametryInetAddressip=clientName=clientFrame.setTitle("DMS端程序V4.0--"+}catch(Exceptione)}}*啟動(dòng)啟動(dòng) 端定時(shí)解析日志,匹配登錄登出日志,向DMS服務(wù)器發(fā)送日*1)*2)*3)*4)在定時(shí)任務(wù)中檢查如果已經(jīng)匹配的日志數(shù)據(jù)達(dá)到發(fā)送門檻數(shù)量就向DMS *5)*6)打 publicvoidstart()finalDMSClientFrameclientFrameif mittedRecFile.exists() mittedRecFile.length() if(unmatchedLogFile.exists()&&unmatchedLogFile.length()>0) timer.schedule(new{ publicvoidrun()(matched.size()>=dataLength)if(sent())mittedLogRec+=}}elseList<LogData>newLogs=clientInfo.catchedLogData+=}}},0,}*privatevoidinitConf()tryconf=newhost=port=interval=dataLength=serverHost=MITTED_REC= UNMATCHED_LOG_FILE=}catch(IOExceptione)thrownewRuntimeException("無法載入配置文件", *連接到服務(wù)器,其中host和portprivatevoidinitSocket()if(host!=null&&port!=null)trysocket=newSocket(host,}catch(Exceptione)thrownewRuntimeException("服務(wù)器連接錯(cuò)誤", }elsethrownewRuntimeException("主機(jī)名或 信息為空 *向DMS*1)*2)*3)通過socket發(fā)送到DMS*4)從socket*5)*6)發(fā)送請(qǐng)求成功返回true,發(fā)送請(qǐng)求失敗返回*@return發(fā)送請(qǐng)求成功返回true,發(fā)送請(qǐng)求失敗返回publicbooleansent()tryDMSRequestrequest=newDMSRequest(matched,DMSResponseresponse=newDMSResponse();intrespCode=if(respCode=={return}return}catch(Exceptione)return}}***@param**publicstaticList<LogData>parseLogData(byte[]logs)List<LogData>list=newfor(intoffset=0;offset<logs.length;offset+=LogDatalogData=newLogData(logs,}return}**1)*2)**3)*publicvoidmatchLogData(List<LogData>newLogs)List<LogData>list=newArrayList<LogData>(newLogs);//本次list.addAll(loginLogs);//上次未匹配的for(LogDatalog:list)//if(log.getType()==LogData.USER_PROCESS)LogDatalogin=//LogReclogRec=matchLogOut(list,//if(logRec!=null)}else ***@param *@param *@return登出日志privatestaticLogRecmatchLogOut(List<LogData>list,LogDataLogReclogRec=newfor(LogDatalog:list)if(logRec.match(log))return return **1)*2)*3)將日志數(shù)據(jù)的toString(*4)private mitted()PrintWriterpw=trypw=newPrintWriter(new for(LogRecrec:matched) }catch(IOExceptione)thrownewRuntimeException("",}finallyif(pw!= **1)* *3)*4)private mitted()BufferedReaderbr=trybr=newBufferedReader(newInputStreamReader(newStringline=while((line=br.readLine())!={LogRecrec=new}}catch(IOExceptione)thrownew}finally(br!=try}catch(IOExceptione)}}}**1)*2)*3)將日志數(shù)據(jù)的toString()*4)privatevoidsaveUnMatched()PrintWriterpw=trypw=newPrintWriter(newfor(LogDatald:loginLogs) }catch(IOExceptione)thrownewRuntimeException("",}finallyif(pw!=}}**1)*2)每行數(shù)*3)*4)privatevoidloadUnMatched()BufferedReaderbr=trybr=newBufferedReader(newInputStreamReader(newStringline=while((line=br.readLine())!=null)LogDataloginLog=new }catch(IOExceptione)thrownewRuntimeException("",}finallyif(br!=try}catch(IOExceptione)} *軟件 **@param*@throws publicstaticvoidmain(String[]args)throwsExceptionDMSClientdmsClient=new}classInfointint//intint// publicStringtoString()SimpleDateFormatsdf=new"yyyy-MM-dd StringBuildersb=newsb.append(sdf.format(newsb.append(StringUtils.rightPad(""++matchedLogRec,+loginLogs.size(),+committedLogRec,+matched.size(),return}}}DMSRequestrequest=newDMSResponseresponse=newDMSResponse(DMSResponse.RESPONSE_CODE_OK);List<LogRec>recList=for(LogRecrec:recList){while(!offerRec(rec));}threadPool.execute(newprivateclassRecReceiveHandlerimplementsRunnableprivateSocketpublicRecReceiveHandler(Socketsocket)this.socket=}publicvoid{DMSServerFrame=thrownew}}}tryDMSRequestrequest=newDMSRequest();DMSResponseresponse=List<LogRec>recList=request.getData();for(LogRecrec:recList){while;}}catch(Exceptione)PrintWriterpw=newPrintWriter(newintsize=logRecQueue.size();for(inti=0;i<size;i++){LogRecrec=if(rec==}recSaveTimer.schedule(newRecSaveHandler(),0,privateclassRecSaveHandlerextendsTimerTaskpublicvoidrun()DMSServerFramedmsServerFrame=DMSServerFrame.getInstance();try{PrintWriterpwnewPrintWriter(newintsize=logRecQueue.size();for(inti=0;i<size;i++){LogRecrec=pollRec();if(rec==null)}}catch(IOException{e.printStackTrace();thrownewRuntimeException("",e);}}}publicclassDMSServerprivateServerSocketprivateExecutorServiceprivateBlockingDeque<LogRec>privateTimerrecSaveTimer;privatePropertiesprivateintport=privateintthreadPoolSize=privateintrecQueueSize=privateintprivateStringlogRecFile="logrecfile.txt";privateMap<String,DMSClientInfo>clientsInfo=.synchronizedMap(newHashMap<String,*創(chuàng)建 *1)*2)*3)*4)*5)publicDMSServer()tryss=newthreadPool=logRecQueue=newrecSaveTimer=newrecSaveTimer.schedule(newRecSaveHandler(),0,}catch(IOExceptione)thrownewRuntimeException("",}}*privatevoidinitConf()tryconf=newport=threadPoolSize=recQueueSize=}catch(IOExceptione)thrownewRuntimeException("無法載入配置文件", *啟動(dòng)DMS*1)* socket服務(wù)器端口,等 端的連*3)如果有連接,就啟 端服務(wù)線程,并且交給線程池執(zhí)*4)繼續(xù)返回*5)*publicvoidstart()DMSServerFramedmsServerFrame=trywhile(true)//服務(wù)器端口,等待端的連Socketsocket=threadPool.execute(new}}catch(Exceptione)} privatestaticclassDMSClientInfoStringintDate publicstaticStringStringBuildersb=newsb.append(StringUtils.rightPad("端名稱",.append(StringUtils.rightPad("累計(jì)請(qǐng)求數(shù)",.append(StringUtils.rightPad("最近請(qǐng)求時(shí)間",.append(StringUtils.rightPad("累計(jì)提交記錄數(shù)",return publicStringtoString()StringBuildersb=newsb.append(StringUtils.rightPad(clientName,+requestNum,+lastRequestTime,+um,return}} privateclassRecReceiveHandlerimplementsRunnable privateSocketsocket; publicRecReceiveHandler(Socketsocket)this.socket=}publicvoidrun()DMSServerFramedmsServerFrametryDMSRequestrequest=newDMSResponseresponseList<LogRec>recList=for(LogRecrec:recList)while;}}catch(Exceptione)thrownewRuntimeException("",}}}privateclassRecSaveHandlerextendsTimerTaskpublicvoidrun()DMSServerFramedmsServerFrame=tryPrintWriterpwintintsize=for(inti=0;i<size;i++){LogRecrec=pollRec();newPrintWriter(new if(rec== }}catch(IOExceptione)thrownew}}}***@paramrec*@return添加成功返回 privatebooleanofferRec(LogRecrec)booleanb=try//向隊(duì)列中插入對(duì)象,插入等待位置超時(shí)時(shí)間是5//如果等待了5秒鐘也沒有等到插入位置,就返回b=logRecQueue.offer(rec,5,}catch(InterruptedExceptione)DMSServerFramedmsServerFrame}return}*從緩沖隊(duì)列中取出一個(gè)LogRec**@returnLogRec對(duì)象,隊(duì)列是空的返回privateLogRecpollRec()DMSServerFramedmsServerFrameLogRecrec=try//從隊(duì)列拉出一個(gè)對(duì)象,不進(jìn)行等待,如果沒有對(duì)象立即返回rec=logRecQueue.poll(0,}catch(InterruptedExceptione)}return}*更新DMS端數(shù)據(jù)發(fā)送信 *@paramrequest服務(wù)器接收到端發(fā)送請(qǐng)求對(duì)privatevoidupdateClientInfo(DMSRequestrequest)StringclientName=DMSClientInfoif(clientsInfo.containsKey(clientName))ci=}elseci=newci.clientName=clientsInfo.put(clientName,}Datedate=newci.lastRequestTime=um }*在界面上顯示 privatevoidprintClientInfo()Stringheader=DMSClientInfo.header();}DMSServerFramedmsServerFramedmsServerFrame.showClientInfo(}publicstaticvoidmain(String[]args)DMSServerserver=new}}StringBuilderbuf=newfor(StringclientName:clientsInfo.keySet())如OS賬號(hào)、進(jìn)程號(hào)、登入時(shí)間、登出時(shí)間、持續(xù)時(shí)長(zhǎng)和終端IP信息,如圖-1所示。圖-圖-圖- ogRecFilePane方法,作為登錄日志數(shù)據(jù)文件顯示/**創(chuàng)建登錄日志數(shù)據(jù)文件顯示面板privateJPanel{JPanelpane=newJLabelheader=newJLabel();JTextArealistArea=newJScrollPanelistPane=newheader.setBounds(10,15,750,listPane.setBounds(10,35,760,Fontmono=newFont("Monospaced",Font.PLAIN,this.logRecArea=return}/**端信息面板privateJPanel{JPanelpane=newJPanel();JLabelheader=new累JTextArealistArea=newJTextArea();JScrollPanelistPane=newJScrollPane(listArea);header.setBounds(10,15,750,listPane.setBounds(10,35,760,Fontmono=newFont("Monospaced",Font.PLAIN,this.clientInfoArea=listArea;returnpane;}**privateJPanelcreateMessagePane()JPanelpane=newJLabelheader=newJTextArealistArea=newJScrollPanelistPane=newJScrollPane(listArea);header.setBounds(10,15,750,listPane.setBounds(10,35,760,Fontmono=newFont("Monospaced",Font.PLAIN,this.messageArea=return privatevoidinit()setTitle("DMS);setSize(800,510);JTabbedPanecontent=newJTabbedPane();content.add("接收到數(shù)據(jù)", 端",content.add("異常消息"}privateDMSServerFrame()}@paramlogRecpublicvoidshowLogRec(LogRec{StringBuilderbuf=newStringBuilder();buf.append(Utils.leftPad(logRec.getUser(),12)); buf.append(Utils.leftPad(logRec.getHost(),}顯 @parampublicvoidshowClientInfo(String{}@parampublicvoidshowException(Exception{StringWriterout=newStringWriter();e.printStackTrace(newPrintWriter(out));messageArea.append(newDate().toString()+"\n");messageArea.append(out.toString()+"\n");}publicclassDMSServerFrameextendsJFrameprivateJTextAreaprivateJTextAreaclientInfoArea;privateJTextAreamessageArea;privatestatic

溫馨提示

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

最新文檔

評(píng)論

0/150

提交評(píng)論