计算机网络原理实验Web服务端.docx
- 文档编号:28791142
- 上传时间:2023-07-19
- 格式:DOCX
- 页数:12
- 大小:404.08KB
计算机网络原理实验Web服务端.docx
《计算机网络原理实验Web服务端.docx》由会员分享,可在线阅读,更多相关《计算机网络原理实验Web服务端.docx(12页珍藏版)》请在冰豆网上搜索。
计算机网络原理实验Web服务端
ExperimentReportofComputerNetwork’sTheory
——WebServer(JAVA)
Designer’sName:
GuidanceCounselors:
Profession:
StudentID:
Content
ExperimentPurpose2
ExperimentRequesting2
DesignIdeasandThought4
CodeDescription6
OperationEffectandResult10
ResultExplanation12
ImprovablePart13
ExperimentConclusion13
1.ExperimentPurpose
1)DealwithaHttpRequest
2)ReceivingandanalyzingaHttpRequest
3)Attaintherequestedfilesfromtheserverfilesystem
4)Establishahttprespondmessageincludingtherequestedfiles
5)Sendthemessagetoclientdirectly
2.ExperimentRequesting
1)WeshouldinstallSDKatfirst,wecanfollowtheguidancegivenby《InstructionofExperiment》.
2)Runthecodewehaveeditedandseetheresultonlywhenwejusthavesomecompileplatformforjava.
3)Forchecktheresult,wecanputtheeditedhtmlfilesintothefolderwhereserverexistsatfirst,thenweshouldopenourbrowserandinputthedirectstringsuchashttp:
//196.168.0.2:
8080/I:
index.htmlintoaddressbar.
4)Follow3),ifwecanjustopenthewebpageandseethecontent,wecanensurethatthewebserverweestablishedisnoproblem.Else,weneedtocheckwherewefailed.
3.DesignIdeaandThought
Wehavejustlearnedaboutthetheoryofhttpprotocolsandgottheknowledgeofserverandclient.Butwhenweeditthecode,thingseemsnottobesoeasy.
Atthisexperiment,weusejavalanguageandeclipsesoftwaretoachieveourgoals.
Firstofall,weneedaclasstoconnectwithourbrowser,forthisidea,weestablishaclasswhichextendsThread.Afterthat,weneedavariabletorecordtheconnectiontimes,whenthenumberbeyondaspecialvalue,wemustclosethewebserver,whichmeansconnectionisfailed!
Then,weneedtocomeupwithawaytosolvesuchaproblemasfollow:
1)HowcantheWebServer“understand”therequestthatourbrowsershavejustsent?
2)Ifthetypeofthisrequestis“get”,howcantheWebServerknowwhichfilesourbrowsersneed?
3)Whilesuchafileorfilesdoesordonotexist,whichactiondoesWebServershouldtake?
(E.g.whatkindofmessagedoesWebServershouldrespondtoourbrowsers?
)
4)Atlast,weneedtoseekforawaythatWebServercansendtherightfileorfilestoclientdirectly.
Onlywhenwesolvetheseproblems,canwereallyestablishatrue-meaningwebserver.
Onthenextpart,wewillshowhowwesolvetheseproblemsbyexplainingthecodewehaveedited!
4.CodeDescription
importjava.io.*;
import.*;
Atthebeginning,weimportedtwomainpackagesthatweneed.
publicclassWebServer{
publicstaticvoidmain(Stringargs[]){//主函数
inti=1,PORT=8080;//端口设置为8080
Wedefinedthesocketnumberweuseis8080
ServerSocketserver=null;//创建一个ServerSocket类,同时在运行该语句的计算机的指定端口处建立一个监听服务
Socketclient=null;//当Client程序需要从Server端获取信息及其他服务时,应创建一个Socket对象
Thenotesweeditedhaveexplainedwell,wedonotexplainmorehere.
try{
server=newServerSocket(PORT);//在8080端口设置监听服务
System.out.println("WebServerislisteningonport"+server.getLocalPort());
//这只是一个测试
Theabovesentenceisnotnecessary,wecandeletesuchsentence.Inourreallife,suchtipswecannotsee.
for(;;){
client=server.accept();//接受客户机的连接请求
newConnectionThread(client,i).start();
i++;//i用于存放请求数
}
}catch(Exceptione){System.out.println(e);}
}
}
Theabovesentenceisimportant,whichisthecoreofMainFunction——weconnectedserverwithclient,andcounttheconnectiontimes.
Wecanseesuchafactthatifthecountnumberisbeyondaspecialvalue,wewouldclosetheserverfromthedefinitionofConnectionThreadFunction.
/*ConnnectionThread类完成与一个Web浏览器的通信*/
classConnectionThreadextendsThread{
Socketclient;//连接Web浏览器的socket字
intcounter;//计数器
publicConnectionThread(Socketcl,intc){//构造函数
client=cl;
counter=c;
}
Constructors’inletparameterisdefinedbyspecificsocketandcurrentconnectionnumber
publicvoidrun()//线程体
{
try{
StringdestIP=client.getInetAddress().toString();//客户机IP地址
intdestport=client.getPort();//客户机端口号
System.out.println(destIP);
System.out.println("Connection"+counter+":
connectedto"+destIP+"onport"+destport+".");
//该语句用于测试
Allthesentencesabout“System.out.println”arenotnecessary,onlyusedfortest,Nolongergiveunnecessarydetailsafter.
PrintStreamoutstream=newPrintStream(client.getOutputStream());
DataInputStreaminstream=newDataInputStream(client.getInputStream());
Stringinline=instream.readLine();//读取Web浏览器提交的请求信息
Fromnowon,it’stimetothecommunicationwhichbetweenserverandclientstarts.System.out.println("Received:
"+inline);//该语句用于测试
if(getrequest(inline)){//如果是GET请求
Stringfilename=getfilename(inline);
Filefile=newFile(filename);
if(file.exists()){//若文件存在,则将文件送给Web浏览器
System.out.println(filename+"requested.");
outstream.println("HTTP/1.0200OK");
outstream.println("MIME_version:
1.0");
outstream.println("Content_Type:
text/html");
intlen=(int)file.length();
outstream.println("Content_Length:
"+len);
outstream.println("");
sendfile(outstream,file);//发送文件
outstream.flush();
}
TheAbovesentencesarebasedontheformofMessagebetweenserverandclient.
else{//文件不存在时
Stringnotfound="Error404-filenotfound";
outstream.println("HTTP/1.0404nofound");
outstream.println("Content_Type:
text/html");
outstream.println("Content_Length:
"+notfound.length()+2);
outstream.println("");
outstream.println(notfound);
outstream.flush();
}
}
longm1=1;
while(m1<11100000){m1++;}//延时
client.close();
}catch(IOExceptione){
System.out.println("Exception:
"+e);
}
}
/*获取请求类型是否为“GET”*/
TheAbovesentencesarebasedontheformatofMessageinwebpageincommonuse.
booleangetrequest(Strings){
if(s.length()>0){
if(s.substring(0,3).equalsIgnoreCase("GET"))returntrue;
}
returnfalse;
}
/*获取要访问的文件名*/
Stringgetfilename(Strings){
Stringf=s.substring(s.indexOf('')+1);
f=f.substring(0,f.indexOf(''));
try{
if(f.charAt(0)=='/')
f=f.substring
(1);
}catch(StringIndexOutOfBoundsExceptione){
System.out.println("Exception:
"+e);
}
if(f.equals(""))f="index.html";
returnf;
}
/*把指定文件发送给Web浏览器*/
voidsendfile(PrintStreamouts,Filefile){
try{
DataInputStreamin=newDataInputStream(newFileInputStream(file));
intlen=(int)file.length();
bytebuf[]=newbyte[len];
in.readFully(buf);
outs.write(buf,0,len);
outs.flush();
in.close();
}catch(Exceptione){
System.out.println("Errorretrievingfile.");
System.exit
(1);
}
}
}
Atlast,wesendtherightfileourbrowsersrequestedtoclient.
5.OperationEffectsandResults
Atfirst,weshouldstatethatourwebsitepathwayis“D:
/workplace/WEB”,andthehtmlfileusedfortestingis“index.html”whichhasbeenputinwebsitefolder.
Then,weneedtofindourIPsite:
Now,let’scheckourWebServer!
1)Runthecodewehaveedited.
2)Inputtherightaddressinourbrowser’saddressbar.
—http:
//219.242.120.11:
8080/D:
/workplace/WEB/index.html
3)Fortunately,wegottherightwebpageweneed!
4)Atlast,wecantestmore——closethewebserver,andinputtheaddressagain,wecanobservesuchsituation!
6.ResultsExplanation
Asallweknow,ourwebserverissuccessful!
Whenweopenourwebserver,itstartstowaitforanyrequestmessagefromclientswherever.Weinputtherightaddress(currentsocketnumberis8080,not80),andwebserverreceiveourrequestandrespondtousbysendingthehtmlfileweneed.
Whileweclosethewebserver,wecannotgettherighthtmlfileafterinputtheaddress,justbecausethesocketnumberof8080ismeaninglessnow.
7.ImportablePart
Nothingisperfect,thereisanapparentweaknessisthatwhenwewanttoclosethewebserver,wemustclosealltheprojectandsoftwarewhichsupportingthecode.It’ssoinconvenient,andwewanttohavethefunctionthatwecaneasilyhandletherunningstateofwebserver,forexample,wewanttoclosethewebserverafter8:
00pmeverydayandopenitinthemorningandsoon.
However,suchfunctionisadditional;wemaynothavethenecessitytoaddafunctionwhosemeaningisalittle.
8.ExperimentConclusion
Weshouldbegladtohavethechancetooperatetheexperimentatfirst,noonecanlearnallonlyfromtheorieswithoutpractices.
Fromsuchanexperiment,wecanacquireadeeperunderstandingaboutHttpProtocolsandtheprocessesofmessagerequireandrespond.Besides,wealsostrengthenourskillofprogrammingeitherinfact.
Generallyspeaking,wecatchthecoreofthehttpprotocols,andachieveouroriginalgoals!
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 计算机网络 原理 实验 Web 服务端