版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認(rèn)領(lǐng)
文檔簡介
JavaSE02DMS4.0——DMSRequest和DMSResponse的設(shè)計和編DMS4.0——發(fā)送功能的設(shè)計和DMS4.0——接收功能的設(shè)計和DMS4.0— 功能的設(shè)計和編寫DMS4.0——服務(wù)端界面的設(shè)計和創(chuàng)建網(wǎng)絡(luò)通信協(xié)議類Protocol,該類設(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ā)送的無連接請求協(xié)議,繼承了ProtocolpublicclassDMSRequestextendsProtocol<List<LogRec>>//協(xié)議中的頭屬性名,表示發(fā)送時間的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ā)送時間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項目中端需要向服務(wù)器端發(fā)送日志數(shù)據(jù),現(xiàn)需要設(shè)計和編寫發(fā)送日志數(shù)據(jù)的privatevoidinitSocket()if(host!=null&&port!=null){trysocket=newSocket(host,}catch(Exception{thrownewRuntimeException("服務(wù)器連接錯誤",}}elsethrownewRuntimeException(}}publicbooleansent()tryDMSRequestrequest=newDMSRequest(matched,DMSResponseresponse=newDMSResponse();intrespCode=if(respCode=={return}return}catch(Exception{;returnfalse;} * 端程序,實現(xiàn) *publicclass{privateLogDataSource/**全部匹配的成對的Log記錄privateList<LogRec>matched=new/**已經(jīng)登錄沒有登出的log記錄,也就是不配對 記錄privateList<LogData>loginLogs=new/**定時器,用于定時獲取日志數(shù)據(jù)源數(shù)據(jù).privateTimer/**匹配成功的登錄日志對privatestatic MITTED_REC= /**已經(jīng)登錄,沒有登出的日志信息privatestaticStringUNMATCHED_LOG_FILE="unmatchedlog.txt";privatePropertiesprivateStringprivateStringprivateintprivateintprivateSocketprivate privateFileprivateInfo/**計費登錄的計算機IP,從配置文 privateStringserverHost; privateStringclientName;publicDMSClient()logDataSource=newtimer=newmittedRecFile=new unmatchedLogFile=newclientInfo=newDMSClientFrameclientFrametryInetAddressip=clientName=clientFrame.setTitle("DMS端程序V4.0--"+}catch(Exceptione)}}*啟動啟動 端定時解析日志,匹配登錄登出日志,向DMS服務(wù)器發(fā)送日*1)*2)*3)*4)在定時任務(wù)中檢查如果已經(jīng)匹配的日志數(shù)據(jù)達到發(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ù)器連接錯誤", }elsethrownewRuntimeException("主機名或 信息為空 *向DMS*1)*2)*3)通過socket發(fā)送到DMS*4)從socket*5)*6)發(fā)送請求成功返回true,發(fā)送請求失敗返回*@return發(fā)送請求成功返回true,發(fā)送請求失敗返回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("無法載入配置文件", *啟動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("累計請求數(shù)",.append(StringUtils.rightPad("最近請求時間",.append(StringUtils.rightPad("累計提交記錄數(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//向隊列中插入對象,插入等待位置超時時間是5//如果等待了5秒鐘也沒有等到插入位置,就返回b=logRecQueue.offer(rec,5,}catch(InterruptedExceptione)DMSServerFramedmsServerFrame}return}*從緩沖隊列中取出一個LogRec**@returnLogRec對象,隊列是空的返回privateLogRecpollRec()DMSServerFramedmsServerFrameLogRecrec=try//從隊列拉出一個對象,不進行等待,如果沒有對象立即返回rec=logRecQueue.poll(0,}catch(InterruptedExceptione)}return}*更新DMS端數(shù)據(jù)發(fā)送信 *@paramrequest服務(wù)器接收到端發(fā)送請求對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賬號、進程號、登入時間、登出時間、持續(xù)時長和終端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等.壓縮文件請下載最新的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)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 售后服務(wù)協(xié)議合同常見問題
- 空調(diào)內(nèi)部結(jié)構(gòu)優(yōu)化質(zhì)保服務(wù)
- 采購合同樣式集錦
- 燈具安裝合同樣本
- 計劃成長擔(dān)保
- 心理測評與咨詢協(xié)議
- 退款協(xié)議書合同范本
- 重建幸福家庭的諾言
- 別墅石材招標(biāo)文件
- 工作責(zé)任保證書樣本
- 靜脈導(dǎo)管常見并發(fā)癥臨床護理實踐指南1
- 學(xué)校學(xué)生勞動教育評價表
- apt攻擊專項應(yīng)急預(yù)案
- 小學(xué)三年級秋季學(xué)期《道德與法治》(統(tǒng)編版)學(xué)習(xí)任務(wù)單(全冊匯總)
- 奧迪A7L汽車說明書
- 美育-美即生活 美育期末試卷及答案
- 網(wǎng)站項目功能測試驗收報告
- 自考02313電力系統(tǒng)微型計算機繼電保護歷年(12-19)真題試卷
- 馬克思主義基本原理智慧樹知到答案章節(jié)測試2023年重慶工商大學(xué)
- 合理性、先進性的證明
- 人教版數(shù)學(xué)三年級上冊分?jǐn)?shù)的初步認(rèn)識分?jǐn)?shù)的初步認(rèn)識-課件16
評論
0/150
提交評論