版權說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權,請進行舉報或認領
文檔簡介
多線程Web服務器
i實驗目的:
用JAVA語言開發(fā)一個多線程的WEB服務器,它能并行服務于多個請求。發(fā)送網(wǎng)頁文獻,
讓網(wǎng)頁文獻可以通過在URL中制定端標語來被瀏覽器使用。
2實驗代碼及截圖
▼I巨http://localhost:8081/index.htm
收藏夾8笆6.11目6,9笆http—www.baidu1首頁
四http://localhost:8081/index.htm
145646-456
☆收藏夾W電6.11鈍6.9*http--www.baidu,首頁J原交通大學g
?卷InternetExplorer無法顯示該網(wǎng)頁
InternetExplorer無法顯示該網(wǎng)頁
您可以嘗試以下操作:
▼更多信息
classConnectionThreadextendsThread{
Socketc1ient;
intcounter;
opub1icConnectionThread(Socketcl,intc){
。。。dient=cl;
,counter=c;
bb}
o
?publicvoidrun()//線程體
。{
。。try{
ob
。StringdestlP=client.getInetAddress().t
oString();//客戶機IP地址
。intdestport=c1ient.getPort();//客戶機端標語
。System.out.println("Connection"+counter+":con
nectedto"+destIP+"onport"+destport+".");
ooPrintStreamoutstream=newPrintStream(c1ient.get
0utputStream());
。。DatalnputStreaminstream=newDataInputStream(clie
nt.getInputStream());
。oStringin1ine=instream.r,eadL.ine();//讀取Web瀏
覽器提交的請求信息
。System.out.print1n("Received:"+inline);
00
00
ooif(getrequest(inline))(//假如是GET請求
?Stringfilename=getfilename(in1ine);
,6o?Fi1efile=newFi1e(filename);
。。?if(file.exists()){//若文獻存在,則將文獻送給Web
瀏覽器
ooSystem.out.println(filename+"requeste
d.");
ooo?outstream.println("HTTP/1.0200OK");
。?ooutstream.printIn("MlME_version:l.0");
o。。outstream,print1n("Content_Type:text/htm
1");
oo?oointlen=(int)file.length();
。。outstream.printin("Content_Length:"+
1en);
ooooooutstream.println("");
?oooo?sendfile(outstream,file);//發(fā)送文獻
so?ooutstream.flush();
。。}else{//文獻不存在時
soStringnotfound="<htm1><headxtitle>Not
Found</title></headxbody><hl>Error404-filenot
found</hl></body></html>";
。。ooutstream.printin("HTTP/1.0404nofou
nd");
。。。outstream.println("Content_Type:text/ht
ml");
。。?outstream.println("Content_Length:"+n
otfound.length()+2);
dooooutstream,println("");
。3booutstrearn,printin(notfound);
outstream.flush();
OdO0}
0
bbb
}
ooolongml=l;
owhile(ml<11100000)
,{
ooml++;
。。}〃延時
oclient.close();
bb3
}catch(lOExceptione){
?System.out.print1n("Exception:"+e);
°}
}
/*獲取請求類型是否為"GET"*/
boo1eangetrequest(Strings){
if(s.length()>0)
{
。if(s.substring(0,3).equaIslgnoreCase("GET"))
returntrue;
}
returnfalse;
)
/*獲取要訪問的文獻名*/
Stringgetfilename(Strings){
0
。Stringf=s.substring(s.indexOf('')+1);
。f=f.substring(0jf.indexOf(''));
6try(
d
if(f.charAt(0)=='/')
oof=f.substring(l);
。}catch(StringIndexOutOfBoundsExceptione){
System.out.println("Exception:"+e);
)
if(f.equals(""))f="index.html";
?returnf;
)
/*把指定文獻發(fā)送給Web瀏覽器*/
voidsendfile(PrintStreamouts,Filefile){
try{
。。DatalnputStreamin=newDatalnputStream(newFileinput
Stream(fi1e));
?int1en=(int)fi1e.length();
?obytebuf[]=newbyte[1en];
。in.readFul1y(buf);
outs,write(buf,0,len);
outs.f1ush();
。。in.close();
o}catch(Exceptione){
b
boSystem.out.println("Errorretrievingfile.");
。System.exit(1);
0
°}
)
)
pub1icclasswebsever{
opublicstaticvoidmain(String[]args){
,IITODOAuto—generatedmethodstub
inti=l,PORT=8081;
ServerSocketserver=nul1;
。Socketdient=nul1;
ostry{
00server=newServerSocket(PORT);
。oSystem.out.print1n("WebServerislisteningon
port"+server.getLocalPort());
00
。whi1e(true){
00
。client=server.accept();//接受客戶機的連
接請求
。。。newConnectionThread(c1ient,i).start。;
。oi++;
}
b
}catch(Exceptione){
。System.out.print1n(e);
)
)
)
3實驗軟硬件環(huán)境
eelipse
Windowsxp
IE瀏覽器
4實驗環(huán)節(jié)
(1)連接:
Web瀏覽器與Web服務器建立連接,打開一個稱為socket(套接字)的虛擬文獻,此文獻
的建立標志著連接建立成功。
(2)請求:
Web瀏覽器通過socket向Web服務器提交請求。HTTP的請求一般是GET或P0ST命
令(POST用于FORM參數(shù)的傳遞)。GET命令的格式為:
GET途徑/文獻名HTTP/1.1
文獻名指出所訪問的文獻,HTTP/1.1指出Web瀏覽器使用的HTTP版本。
(3)應答:
Web瀏覽器提交請求后,通過HTTP協(xié)議傳送給Web服務器。Web服務器接到后,進行事
務解決,解決結果又通過HTTP傳回給Web瀏覽器,從而在Web瀏覽器上顯示出所請求的頁
面。
為了告知Web瀏覽器傳送內(nèi)容的類型,Web服務器一方面?zhèn)魉鸵恍〩TTP頭信息,然
后傳送具體內(nèi)容(即HTTP體信息),HTTP頭信息和HTTP體信息之間用一個空行分開。
(4)關閉連接:
當應答結束后,Web瀏覽器與Web服務器必須斷開,以保證其它Web瀏覽器可以與Web
服務器建立連接。
5實驗心得
Java中實現(xiàn)多線程有兩種途徑:繼承Thread類或者實現(xiàn)Runnable接口。此處使用
了接口的方式生成線程,由于接口可以實現(xiàn)多繼承,況且Runnable只有一個run方法,很適
合繼承。在使用Thread的時候只需繼承Thread,并且new一個實例出來,調(diào)用start
()方法即可以啟動一個線程。
在本次實驗中,通過用java語言開發(fā)一個多線程的web服務器,能并行服務于多個
請求,來掌握套接字編程技術,了解并運用http協(xié)議的作用原理,實現(xiàn)多線程web服務
器設計。
6參考文獻:,
1計算機網(wǎng)絡:自頂向下方法(原書第4版)/(美)庫羅斯(Kurose,J.F.)等著;陳鳴譯一
北京:機械工業(yè)出版社,2023.12
2java從入門到精通:李鐘尉,馬文強,陳丹丹等編著;一清華大學出版社,2023.9
3實驗指導書
郵件客戶機
1實驗目的:
。為發(fā)送者提供一個圖形界面,其中包含:發(fā)送電子郵件地址、接受者電子郵件地址、郵件主
題和自身。開發(fā)一個Internet上的使用STMP協(xié)議的網(wǎng)絡服務器的郵件客戶端,在W
indowsXP,Windows7系統(tǒng)下,使用JAVA語言開發(fā),并最終運營該程序。
2實驗部分代碼及截圖:
在發(fā)件人框中填寫相應的信息,點擊發(fā)送按鈕即可向目的郵箱發(fā)送郵件。
1025674623@qq.comX
作業(yè)2:郵件客戶機
102567'1623<1025674623@>
你0!這是T詢試斜*
刪除解件41/5?
提示I區(qū)
①信息已成功發(fā)送!
確定
publicclassMaiIMessage{
publicstaticvoidmain(String[]args){
。EventQueue.invokeLater(newRunnable(){
?publicvoidrun(){
try(
。。SendFrameframe=newSendFrame();
Mframe.setVisib1e(true);
e。。}catch(Exceptione){
。ge.printStackTrace();}
/**
。*Createtheframe.
0*/
pub1icSendFrame(){
ethisFrame=this;
gsetTitle(nJavaMailclient");
setDefaultC1oseOperation(JFrame,EXIT_ON_CLOSE);
setBounds(100,100,450,328);
contentPane=newJPane1();
“contentPane.setBorder(newEmptyBorder(5,5,5,5));
^setContentPane(contentPane);
?contentPane.setLayout(null);
。JLabelIblFrom=newJLabel(ufrom:*');
oolblFrom.setBounds(10,10,54,22);
?contentPane.add(lblFrom);
0
gJLabe1IblTo=newJLabel(nTo:");
o1blTo.setBounds(l0,42,42,22);
contentPane.add(IblTo);
sJLabe1lb1Subject=newJLabe1(HSubject:");
4bISubject.setBounds(10,74,54,22);
oocontentPane.add(lblSubject);
b
txt_From=newJTextField();
8txt_From.setEditable(fa1se);
—From.setText(,H,);
?txt_From.setBounds(49,11,383,21);
^contentPane.add(txt_From);
。txt_From.setColumns(10);
“xt_To=newJTextField();
txt_To.setText("n);
otxt_To.setColumns(10);
。txt_To.setBounds(49,42,383,21);
contentPane,add(txt_To);
gtext_Subject=newJTextFie1d();
otext_Subject.setText("作業(yè)2:郵件客戶機)
4ext_Subject.setColumns(10);
??text_Subject.setBounds(66,73,366,21);
contentPane.add(text_Subject);
0
。JLabelIblMassage=newJLabel(nMassage:'1);
?lblMassage.setBounds(10,101,64,15);
contentPane.add(IblMassage);
00
00
gjButtonbtnQuit=newJButton("Quit");
abtnQuit.addActionListener(newActionListener(){
叩ublievoidactionPerformed(ActionEvente){
。。4hisFrame.dispose();
00}
0});
?btnQuit.setBounds(295,271,137,23);
contentPane.add(btnQuit);
0
。JScro11PanescrollPane=newJScro11Pane();
scrollPane.setBounds(10,229,422,-101);
contentPane.add(scroUPane);
。Pane1pane1=newPanel();
。panel.setBounds(10,115,422,156);
?contentPane.add(pane1);
pane1.setLayout(null);
00
dScrollPanescro11Pane_1=newScrollPane();
。scrollPane_1.setBounds(0,0,422,156);
epanel.add(scro1IPane_1);
ina1TextAreaSend_TextArea=newTextArea();
gSend_TextArea.setText("你好!這是一封測試郵件”);
。Send_TextArea.setBounds(0,0,440,170);
scroHPane_l.add(Send_TextArea);
JButtonbtnSend=newJButton("Sendn);
btnSend.addActionListener(newActionListener(){
。pub1icvoidactionPerformed(ActionEvente){
。oStringtxtfrom=txt_From.getText();
。。oStringtxtto=txt_To.getText();
“Stringtxtsubject=text_Subject.getText();
gStringsendtextarea=Send_TextArea.getText();
000
8try{
gMaiIMessagemessage=newMai1Message();
0000message.setFrom(txtfrom);//發(fā)件人
ooomessage.setTo(txtto);//收件人
a。。Stringserver="”;//郵件服務器smtp.qq.com
ogmessage.setSubject(txtsubject);〃郵件主題
的message.setContent(sendtextarea);〃郵件內(nèi)容
。。。message.setDatafrom(txtfrom);〃發(fā)件人,在郵件的發(fā)件人欄目中顯示
。gomessage.setDatato(txtto);〃收件人,在郵件的收件人欄目中顯示
。。message.setUser("”);〃登陸郵箱的用戶名
message,setPassword(”zjr*******(保密)");〃登陸郵箱的密碼
00
。。SendFramesmtp=newSendFrame(server,25);
。booleanflag;
0
8f1ag=smtp.sendMail(message,server);
000
。8if(flag){
aJ0ptionPane.showMessageDialog(nu11,"信息已成功發(fā)送!二
提醒:JOPtionPane.INF0RMAT10N_MESSAGE);
000b}
。。else{
。。JOptionPane.showMessageDia1og(nu11,"郵件發(fā)送失敗!”,
提醒*JOptionPane.INFORMATION_MESSAGE);
0)
g//System.out.println("iuhfihulaeihba");
g3}catch(UnknownHostExceptionel){
0gg〃TODOAuto-generatedcatchblock
ge1.printStackTrace();
o。。。}catch(IOExceptionel){
g。//TOD0Auto—generatedcatchbiock
。。1.printStackTrace();
/AoJOptionPane.showMessageDialog(null,”信息已成功發(fā)送!“提醒”,JOption
Pane.INF0RMATION_MESSAGE);
/AeSystem.out.print1n(txtfrom+”\n"+txtto+”\n"+txtsubject+'*\
n^+sendtextarea);
00j
06));
。由tnSend.setBounds(10,271,144,23);
ocontentPane.add(btnSend);
。JButtonbtnC1ear=newJButton("Clear");
btnClear.addActionListener(newActionListener(){
。?publievoidactionPerformed(ActionEvente){
。txt_To.setText(u");
text_Subject.setText("");
gSend_TextArea.setText("");
。oJOptionPane.showMessageDialog(null,”信息刪除成功匕“提醒”,J
0ptionPane.INFORMATION_MESSAGE);
00|
。});
btnClear.setBounds(149,271,150,23);
?contentPane.add(btnClear);
}
privatebooleandebug=true;
3BASE64Encoderencode=newBASE64Encoder();〃用于力口密后發(fā)送用戶名和
密碼
oprivateSocketsoeket;
publicSendFrame(Stringserver,intport)throwsUnknownHostExcepti
on,lOException{
。try(
。socket=newSocket(server,25);
o}catch(SocketExceptione){
//System,out.print1n(e.getMessage());
o}catch(Exceptione){
e.printStackTrace();
}finally{
//System.out.pr已經(jīng)建立連接!)
)
0}
。//注冊到郵件服務器
。publicvoidhelo(Stringserver,BufferedReaderin,BufferedWriterout)
throwsIOException{
。intresu1t:
oresult=getResult(in);
。//連接上郵件服務后,服務器給出220應答
if(result!=220){
thrownew10Exception("連接服務器失敗”);
0)
。result=sendServer("HELOH+server,in,out);
。//HELO命令成功后返回250
。if(result!=250)
0{
othrownewIOException("注冊郵件服務器失敗!");
。privateintsendServer(Stringstr,BufferedReaderin,BufferedWr
iterout)throwsI0Exception{
out,write(str);
。out.newLine();
。out.flushO;
oif(debug)
°{
〃。System.out.println(M已發(fā)送命令:"+str);
)
returngetResult(in);
°}
publicintgetResuit(BufferedReaderin){
oString1ine="n;
try(
line=in.readLine();
if(debug){
//System.out.println(M服務器返回狀態(tài):"+line);
0}
}catch(Exceptione){
oe.printStackTrace();
°}
。//從服務器返回消息中讀出狀態(tài)碼,將其轉換成整數(shù)返回
oStringTokenizerst=newStringTokenizer(1ine,"");
oreturninteger.parselnt(st.nextToken());
)
0
。publicvoidauthLogin(MailMessagemessage,BufforedReaderin,Buf
feredWriterout)throwsIOException{
intresult;
。resu1t=sendServer("AUTHLOGIN",in,out);
if(resu1t!=334){
thrownewIOException("用戶驗證失敗!");
°}
。result=sendServer(encode.encode(message.getUser().getBytes()),in,ou
t);
。if(result!=334){
othrownewI0Exc叩tion("用戶名錯誤!”);
)
resuIt=sendServer(encode.encode(message.getPa
ssword().getBytes()),in,out);
if(result!=235){
。thrownewlOExc叩tion(M驗證失??!”);
)
)
//開始發(fā)送消息,郵件源地址
publicvoidmai1from(Stringsource,BufferedReaderin,Buffer
edWriterout)throws10Exception{
。intresuIt;
result=sendServer(nMAILFROM:<"+source+u>",in,out);
if(result!=250){
。thrownewlOException("指定源地址錯誤”);
0}
0}
。//設立郵件收件人
publicvoidrcpt(Stringtouchman,BufferedReaderin,BufferedWriterou
t)throwsIOException{
。intresu1t;
。result=sendServer(nRCPTTO:<"+touchman+">n,in,out);
if(result!=250){
thrownewlOException("指定目的地址錯誤!M);
〃郵件體
〃退出
publievoidquit(BufferedReaderin,BufferedWriterout)throwsIO
Exception{
。intresult;
result=sendServer("QUIT",in,out);
)
0
〃發(fā)送郵件主程序
pub1icboo1eansendMail(MailMessagemessage,S
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經(jīng)權益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
- 6. 下載文件中如有侵權或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 中國嘧啶核苷行業(yè)市場前景預測及投資價值評估分析報告
- 2026年1月24日山東省選調(diào)生面試真題及答案解析(下午卷)
- 2026年生物基可降解塑料項目投資計劃書
- 牛羊販運人員培訓課件教學
- 環(huán)境局公文寫作培訓課件
- 小學科學教師的個人年度工作總結
- 社區(qū)就業(yè)與再就業(yè)年度工作總結
- 2025年國家公務員錄用考試公共基礎知識全真模擬題庫及答案
- 2025年全國高壓電工作業(yè)人員操作證考試題庫(含答案)
- 土方工程三級安全教育試題(附答案)
- 2025年公務員時事政治熱點試題解析+答案
- 免疫聯(lián)合治療的生物樣本庫建設
- 項目管理溝通矩陣及問題跟進器
- 交通運輸企業(yè)人力資源管理中存在的問題及對策
- 蒂森電梯安全質(zhì)量培訓
- 設備供貨進度計劃及保證措施
- 純化水取樣課件
- 2025年四川單招護理試題及答案
- 鋼梁現(xiàn)場安裝施工質(zhì)量通病、原因分析及應對措施
- 山東省青島市市南區(qū)2024-2025學年六年級上學期期末考試數(shù)學試卷
- 安全生產(chǎn)責任追究細則
評論
0/150
提交評論