实验七应用层网络编程一.docx
- 文档编号:23094783
- 上传时间:2023-04-30
- 格式:DOCX
- 页数:18
- 大小:176.11KB
实验七应用层网络编程一.docx
《实验七应用层网络编程一.docx》由会员分享,可在线阅读,更多相关《实验七应用层网络编程一.docx(18页珍藏版)》请在冰豆网上搜索。
实验七应用层网络编程一
浙江大学城市学院实验报告
课程名称计算机网络应用
实验项目名称实验七应用层网络编程
(一)
实验成绩指导老师(签名)日期2014-06-03
一.实验目的和要求
1.通过实现使用Java应用层客户端和服务器来获得关于使用JavaSocket网络编程的经验(SMTP、POP3)。
二.实验内容、原理及实验结果与分析
1.SMTP编程(参考电子讲义“网络编程参考资料-应用层.pdf”及教材“第2章Socket编程”)
阅读“网络编程参考资料-应用层.pdf”中8.3.1部分,实现“SMTP客户机实现”的源代码(SMTPClientDemo.java),并在机器上编译运行通过。
(注:
可输入城院SMTP邮件服务器或其他邮件服务器作为SMTP服务器)
【程序源代码】
SMTPClientDemo.java
importjava.io.*;
import.*;
importjava.util.*;
//Chapter8,Listing1
publicclassSMTPClientDemo{
protectedintport=25;
protectedStringhostname="localhost";
protectedStringfrom="";
protectedStringto="";
protectedStringsubject="";
protectedStringbody="";
protectedSocketsocket;
protectedBufferedReaderbr;
protectedPrintWriterpw;
//ConstructsanewinstanceoftheSMTPClient
publicSMTPClientDemo()throwsException{
try{
getInput();
sendEmail();
}catch(Exceptione){
System.out.println("Errorsendingmessage-"+e);
}
}
publicstaticvoidmain(String[]args)throwsException{
//StarttheSMTPclient,soitcansendmessages
SMTPClientDemoclient=newSMTPClientDemo();
}
//ChecktheSMTPresponsecodeforanerrormessage
protectedintreadResponseCode()throwsException{
Stringline=br.readLine();
System.out.println("<"+line);
line=line.substring(0,line.indexOf(""));
returnInteger.parseInt(line);
}
//Writeaprotocolmessagebothtothenetworksocketandtothescreen
protectedvoidwriteMsg(Stringmsg)throwsException{
pw.println(msg);
pw.flush();
System.out.println(">"+msg);
}
//Closeallreaders,streamsandsockets
protectedvoidcloseConnection()throwsException{
pw.flush();
pw.close();
br.close();
socket.close();
}
//SendtheQUITprotocolmessage,andterminateconnection
protectedvoidsendQuit()throwsException{
System.out.println("SendingQUIT");
writeMsg("QUIT");
readResponseCode();
System.out.println("ClosingConnection");
closeConnection();
}
//SendanemailmessageviaSMTP,adheringtotheprotocolknownasRFC2821
protectedvoidsendEmail()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("Sendinghelocommand");
writeMsg("HELO"+InetAddress.getLocalHost().getHostName());
code=readResponseCode();
if(code!
=250){
sendQuit();
thrownewException("InvalidSMTPServer");
}
System.out.println("Sendingmailfromcommand");
writeMsg("MAILFROM:
<"+this.from+">");
code=readResponseCode();
if(code!
=250){
sendQuit();
thrownewException("Invalidfromaddress");
}
System.out.println("Sendingrcpttocommand");
writeMsg("RCPTTO:
<"+this.to+">");
code=readResponseCode();
if(code!
=250){
sendQuit();
thrownewException("Invalidtoaddress");
}
System.out.println("Sendingdatacommand");
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");
else
System.out.println("Messagesent");
}
//Obtaininputfromtheuser
protectedvoidgetInput()throwsException{
//Readinputfromuserconsole
Stringdata=null;
BufferedReaderbr=newBufferedReader(newInputStreamReader(System.in));
//RequesthostnameforSMTPserver
System.out.print("PleaseenterSMTPserverhostname:
");
data=br.readLine();
if(data==null||data.equals(""))hostname="localhost";
elsehostname=data;
//Requestthesender'semailaddress
System.out.print("PleaseenterFROMemailaddress:
");
data=br.readLine();
from=data;
//Requesttherecipient'semailaddress
System.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.onablankline
Stringline=br.readLine();
while(line!
=null){
//Checkfora'.',andonlya'.',onaline
if(line.equalsIgnoreCase(".")){
break;
}
buffer.append(line);
buffer.append("\n");
line=br.readLine();
}
buffer.append(".\n");
body=buffer.toString();
}
}
【实验结果与分析】
2.POP3编程(参考电子讲义“网络编程参考资料-应用层.pdf”及教材“第2章Socket编程”)
阅读“网络编程参考资料-应用层.pdf”中8.3.2部分,实现“POP3客户实现”的源代码(Pop3ClientDemo.java),并在机器上编译运行通过。
(注:
可输入城院POP3邮件服务器或其他邮件服务器作为POP3服务器)
【程序源代码】
Pop3ClientDemo.java
importjava.io.*;
import.*;
importjava.util.*;
publicclassPop3ClientDemo{
protectedintport=110;
protectedStringhostname="localhost";
protectedStringusername="";
protectedStringpassword="";
protectedSocketsocket;
protectedBufferedReaderbr;
protectedPrintWriterpw;
//ConstructsanewinstanceofthePOP3client
publicPop3ClientDemo()throwsException{
try{
//Getuserinput
getInput();
//Getmailmessages
displayEmails();
}catch(Exceptione){
System.err.println("Erroroccured-detailsfollow");
e.printStackTrace();
System.out.println(e.getMessage());
}
}
//ReturnsTRUEifPOPresponseindicatessuccess,FALSEiffailure
protectedbooleanresponseIsOk()throwsException{
Stringline=br.readLine();
System.out.println("<"+line);
//和SMTP不同的地方,POP3的回覆不再是一個number而是
//+OK來代表要求成功。
失敗則以-ERR來代表。
returnline.toUpperCase().startsWith("+OK");
}
//ReadsalinefromthePOPserver,anddisplaysittoscreen
protectedStringreadLine(booleandebug)throwsException{
Stringline=br.readLine();
//Appenda if(debug) System.out.println("<"+line); else System.out.println(line); returnline; } //WritesalinetothePOPserver,anddisplaysittothescreen protectedvoidwriteMsg(Stringmsg)throwsException{ pw.println(msg); pw.flush(); System.out.println(">"+msg); } //Closeallwriters,streamsandsockets protectedvoidcloseConnection()throwsException{ pw.flush(); pw.close(); br.close(); socket.close(); } //SendtheQUITcommand,andcloseconnection protectedvoidsendQuit()throwsException{ System.out.println("SendingQUIT"); writeMsg("QUIT"); readLine(true); System.out.println("ClosingConnection"); closeConnection(); } //Displayemailsinamessage protectedvoiddisplayEmails()throwsException{ BufferedReaderuserinput=newBufferedReader(new InputStreamReader(System.in)); System.out.println("Displayingmailboxwithprotocolcommands"+ "andresponsesbelow"); System.out.println("-----------------------------------------"+ "---------------------"); //OpenaconnectiontoPOP3server System.out.println("OpeningSocket"); socket=newSocket(this.hostname,this.port); br=newBufferedReader(newInputStreamReader(socket.getInputStream())); pw=newPrintWriter(newOutputStreamWriter(socket.getOutputStream())); //Ifresponsefromserverisnotokay if(! responseIsOk()){ socket.close(); thrownewException("InvalidPOP3Server"); } //LoginbysendingUSERandPASScommands System.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"); //...andparsefornumberofmessages Stringline=readLine(true); StringTokenizertokens=newStringTokenizer(line,""); //+OK tokens.nextToken(); //numberofmessages intmessages=Integer.parseInt(tokens.nextToken()); //sizeofallmessages intmaxsize=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(); } //Readuserinput protectedvoidgetInput()throwsException{ Stringdata=null; BufferedReaderbr=newBufferedReader(newInputStreamReader(System.in))
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 实验七 应用层网络编程一 实验 应用 网络 编程