实验七 应用层网络编程一_第1页
实验七 应用层网络编程一_第2页
实验七 应用层网络编程一_第3页
实验七 应用层网络编程一_第4页
实验七 应用层网络编程一_第5页
已阅读5页,还剩5页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

..大学城市学院实验报告课程名称计算机网络应用实验工程名称实验七应用层网络编程〔一〕实验成绩指导教师〔签名〕日期2014-06-03一.实验目的和要求通过实现使用Java应用层客户端和效劳器来获得关于使用JavaSocket网络编程的经历〔SMTP、POP3〕。二.实验容、原理及实验结果与分析SMTP编程〔参考电子讲义"网络编程参考资料-应用层.pdf〞及教材"第2章Socket编程〞〕阅读"网络编程参考资料-应用层.pdf〞中8.3.1局部,实现"SMTP客户机实现〞的源代码〔SMTPClientDemo.java〕,并在机器上编译运行通过。〔注:可输入城院SMTP效劳器.或其他效劳器作为SMTP效劳器〕【程序源代码】SMTPClientDemo.javaimportjava.io.*;import.*;importjava.util.*;//Chapter8,Listing1publicclassSMTPClientDemo{protectedintport=25;protectedStringhostname="localhost";protectedStringfrom="";protectedStringto="";protectedStringsubject="";protectedStringbody="";protectedSocketsocket;protectedBufferedReaderbr;protectedPrintWriterpw;//ConstructsanewinstanceoftheSMTPClientpublicSMTPClientDemo()throwsException{try{getInput();sendEmail();}catch(Exceptione){System.out.println("Errorsendingmessage-"+e);}}publicstaticvoidmain(String[]args)throwsException{ //StarttheSMTPclient,soitcansendmessages SMTPClientDemoclient=newSMTPClientDemo();}//ChecktheSMTPresponsecodeforanerrormessageprotectedintreadResponseCode()throwsException{Stringline=br.readLine();System.out.println("<"+line);line=line.substring(0,line.indexOf(""));returnInteger.parseInt(line);}//WriteaprotocolmessagebothtothenetworksocketandtothescreenprotectedvoidwriteMsg(Stringmsg)throwsException{pw.println(msg);pw.flush();System.out.println(">"+msg);}//Closeallreaders,streamsandsocketsprotectedvoidcloseConnection()throwsException{pw.flush();pw.close();br.close();socket.close();}//SendtheQUITprotocolmessage,andterminateconnectionprotectedvoidsendQuit()throwsException{System.out.println("SendingQUIT");writeMsg("QUIT");readResponseCode();System.out.println("ClosingConnection");closeConnection();}//SendanemailmessageviaSMTP,adheringtotheprotocolknownasRFC2821protectedvoidsendEmail()throwsException{System.out.println("Sendingmessagenow:Debugbelow");System.out.println("---------------------------------"+"-----------------------------");System.out.println("OpeningSocket");socket=newSocket(this.hostname,this.port);System.out.println("CreatingReader&Writer");br=newBufferedReader(newInputStreamReader(socket.getInputStream()));pw=newPrintWriter(newOutputStreamWriter(socket.getOutputStream()));System.out.println("Readingfirstline");intcode=readResponseCode();if(code!=220){socket.close();thrownewException("InvalidSMTPServer");}System.out.println("Sendinghelomand");writeMsg("HELO"+InetAddress.getLocalHost().getHostName());code=readResponseCode();if(code!=250){sendQuit();thrownewException("InvalidSMTPServer");}System.out.println("Sendingmailfrommand");writeMsg("MAILFROM:<"+this.from+">");code=readResponseCode();if(code!=250){sendQuit();thrownewException("Invalidfromaddress");}System.out.println("Sendingrcpttomand");writeMsg("RCPTTO:<"+this.to+">");code=readResponseCode();if(code!=250){sendQuit();thrownewException("Invalidtoaddress");}System.out.println("Sendingdatamand");writeMsg("DATA");code=readResponseCode();if(code!=354){sendQuit();thrownewException("Dataentrynotaccepted");}System.out.println("Sendingmessage");writeMsg("Subject:"+this.subject);writeMsg("To:"+this.to);writeMsg("From:"+this.from);writeMsg("");writeMsg(body);code=readResponseCode();sendQuit();if(code!=250)thrownewException("Messagemaynothavebeensentcorrectly");elseSystem.out.println("Messagesent");}//ObtaininputfromtheuserprotectedvoidgetInput()throwsException{//ReadinputfromuserconsoleStringdata=null;BufferedReaderbr=newBufferedReader(newInputStreamReader(System.in));//RequesthostnameforSMTPserverSystem.out.print("PleaseenterSMTPserverhostname:");data=br.readLine();if(data==null||data.equals(""))hostname="localhost";elsehostname=data;//Requestthesender'semailaddressSystem.out.print("PleaseenterFROMemailaddress:");data=br.readLine();from=data;//Requesttherecipient'semailaddressSystem.out.print("PleaseenterTOemailaddress:");data=br.readLine();if(!(data==null||data.equals("")))to=data;System.out.print("Pleaseentersubject:");data=br.readLine();subject=data;System.out.println("Pleaseenterplain-textmessage('.'character"+"onablanklinesignalsendofmessage):");StringBufferbuffer=newStringBuffer();//Readuntiluserentersa.onablanklineStringline=br.readLine();while(line!=null){//Checkfora'.',andonlya'.',onalineif(line.equalsIgnoreCase(".")){break;}buffer.append(line);buffer.append("\n");line=br.readLine();}buffer.append(".\n");body=buffer.toString();}}【实验结果与分析】POP3编程〔参考电子讲义"网络编程参考资料-应用层.pdf〞及教材"第2章Socket编程〞〕阅读"网络编程参考资料-应用层.pdf〞中8.3.2局部,实现"POP3客户实现〞的源代码〔Pop3ClientDemo.java〕,并在机器上编译运行通过。〔注:可输入城院POP3效劳器.或其他效劳器作为POP3效劳器〕【程序源代码】Pop3ClientDemo.javaimportjava.io.*;import.*;importjava.util.*;publicclassPop3ClientDemo{protectedintport=110;protectedStringhostname="localhost";protectedStringusername="";protectedStringpassword="";protectedSocketsocket;protectedBufferedReaderbr;protectedPrintWriterpw;//ConstructsanewinstanceofthePOP3clientpublicPop3ClientDemo()throwsException{try{//GetuserinputgetInput();//GetmailmessagesdisplayEmails();}catch(Exceptione){System.err.println("Erroroccured-detailsfollow");e.printStackTrace();System.out.println(e.getMessage());}}//ReturnsTRUEifPOPresponseindicatessuccess,FALSEiffailureprotectedbooleanresponseIsOk()throwsException{Stringline=br.readLine();System.out.println("<"+line);//和SMTP不同的地方,POP3的回覆不再是一個number而是//+OK來代表要求成功。失敗則以-ERR來代表。returnline.toUpperCase().startsWith("+OK");}//ReadsalinefromthePOPserver,anddisplaysittoscreenprotectedStringreadLine(booleandebug)throwsException{Stringline=br.readLine();//Appenda<charactertoindicatethisisaserverprotocolresponseif(debug)System.out.println("<"+line);elseSystem.out.println(line);returnline;}//WritesalinetothePOPserver,anddisplaysittothescreenprotectedvoidwriteMsg(Stringmsg)throwsException{pw.println(msg);pw.flush();System.out.println(">"+msg);}//Closeallwriters,streamsandsocketsprotectedvoidcloseConnection()throwsException{pw.flush();pw.close();br.close();socket.close();}//SendtheQUITmand,andcloseconnectionprotectedvoidsendQuit()throwsException{System.out.println("SendingQUIT");writeMsg("QUIT");readLine(true);System.out.println("ClosingConnection");closeConnection();}//DisplayemailsinamessageprotectedvoiddisplayEmails()throwsException{BufferedReaderuserinput=newBufferedReader(newInputStreamReader(System.in));System.out.println("Displayingmailboxwithprotocolmands"+"andresponsesbelow");System.out.println("-----------------------------------------"+"---------------------");//OpenaconnectiontoPOP3serverSystem.out.println("OpeningSocket");socket=newSocket(this.hostname,this.port);br=newBufferedReader(newInputStreamReader(socket.getInputStream()));pw=newPrintWriter(newOutputStreamWriter(socket.getOutputStream()));//Ifresponsefromserverisnotokayif(!responseIsOk()){socket.close();thrownewException("InvalidPOP3Server");}//LoginbysendingUSERandPASSmandsSystem.out.println("Sendingusername");writeMsg("USER"+this.username);if(!responseIsOk()){sendQuit();thrownewException("Invalidusername");}System.out.println("Sendingpassword");writeMsg("PASS"+this.password);if(!responseIsOk()){sendQuit();thrownewException("Invalidpassword");}//Getmailcountfromserver....System.out.println("Checkingmail");writeMsg("STAT");//...andparsefornumberofmessagesStringline=readLine(true);StringTokenizertokens=newStringTokenizer(line,"");//+OKtokens.nextToken();//numberofmessagesintmessages=Integer.parseInt(tokens.nextToken());//sizeofallmessagesintmaxsize=Integer.parseInt(tokens.nextToken());if(messages==0){System.out.println("Therearenomessages.");sendQuit();return;}System.out.println("Thereare"+messages+"messages.");System.out.println("Pressentertocontinue.");userinput.readLine();for(inti=1;i<=messages;i++){System.out.println("Retrievingmessagenumber"+i);writeMsg("RETR"+i);System.out.println("--------------------");line=readLine(false);while(line!=null&&!line.equals(".")){line=readLine(false);}System.out.println("--------------------");System.out.println("Pressentertocontinue.Tostop,"+"typeQthenenter");Stringresponse=userinput.readLine();if(response.toUpperCase().startsWith("Q"))break;}sendQuit();}publicstaticvoidmain(String[]args)throwsException{Pop3ClientDemoclient=newPop3ClientDemo();}//ReaduserinputprotectedvoidgetInput()throwsException{Stringdata=null;BufferedReaderbr=newBufferedReader(newInputStreamReader(System.in));System.out.p

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论