用Java實現Web伺服器 HTTP協議

來源:互聯網
上載者:User
用Java實現Web伺服器

廣西財政高等專科學校 徐 輝

  一、HTTP協議的作用原理

  HTTP協議的作用原理包括四個步驟:

1.串連:Web瀏覽器與Web伺服器建立串連。2.請求:Web瀏覽器通過socket向Web伺服器提交請求。3.應答:Web瀏覽器提交請求後,通過HTTP傳送給Web伺服器。Web伺服器接到請求後,進行交易處理,處理結果又通過HTTP傳回給Web瀏覽器,從而在Web瀏覽器上顯示出所請求的頁面。4.關係串連:當應答結束後,Web瀏覽器與Web伺服器必須斷開,以保證其它Web瀏覽器能夠與Web伺服器建立串連。

二、用Java實現Web伺服器的程式設計

  根據上述HTTP協議的作用原理,實現GET請求的Web伺服器程式的方法如下:

1.建立ServerSocket類對象,監聽連接埠8080。這是為了區別於HTTP的標準TCP/IP連接埠80而取的;2.等待、接受客戶機串連到連接埠8080,得到與客戶機串連的socket;3.建立與socket關聯的輸入資料流instream和輸入出流outstream;
式為:GET路徑/檔案名稱HTTP/1.0;4.從與socket關聯的輸入資料流instream中讀取一行客戶機提交的請求資訊,請求資訊的格式為:GET路徑/檔案名稱HTTP/1.0;5.從請求資訊中擷取請求類型。如果請求類型是GET,則從請求資訊中擷取所訪問的HTML檔案名稱。沒有HTML檔案名稱時,則以index.htm1作為檔案名稱;6.如果HTML檔案存在,則開啟HTML檔案,把HTTP頭資訊和HTML檔案內容通過socket傳回給Web伺服器,然後關閉檔案,否則發送錯誤資訊給Web瀏覽器;7.關閉與相應Web瀏覽器串連的socket字。

  下面的程式是根據上述方法編寫的,可實現多線程的Web伺服器,以保證多個客戶機能同時與該Web伺服器串連。

 //WebServer.java用Java編寫Web伺服器

 import java.io.*;

 import java.net.*;

 import java.util.Date;

 public class WebServer{

 public static void main(String args[])

{

 int i=1,PORT=8080;

 ServerSocket server=null;

 Socketclient=null;

 try{

 server=new ServerSocket(PORT);

 System.out.println

("Web Server is listening on port"

+server.getLocalPort());

 for(;;){

 client=server.accept();

//接受客戶機的串連請求

 new Connection Thread(client,i).start();

 i++;

 }

 }catch(Exception e){System.out.println(e);}

 }

 }

/*Connnection Thread類完成

與一個Web瀏覽器的通訊*/

 class Connection Thread extends Thread{

 Socket client;//串連Web瀏覽器的socket字

 int counter;//計數器

 public Connection Thread(Socketcl,int c){

 client=cl;

 counter=c;

 }

 public void run()//線程體

 {

 try{

 String deskIP=client.getInetAddress().toString();

//客戶機IP地址

 int destport=client.getPort();

//客戶機連接埠號碼

 System.out.println

("Connecction"+counter+":

connected to "+destIP+"on port

 "+destport+".");

 PrintStream outstream=new printStream

(client.getOoutputStream());

 DataInputStreaminstream+new DataInputStream

(client.getInputStream());

 String inline=instream.readLine();

//讀取Web瀏覽器提交的請求資訊

 System.out.println("Received:"+inline);

 if(getrequest(inline)){//如果是GET請求

 String filename=getfilename(inline);

 File file=new File (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/htm1");

 int len=(int)file.length();

 outstream.println("Content_Length:"+len);

 outstream.println("");

 sendfile(outstream,file);//傳送檔案

 outstream.flush();

 }else{//檔案不存在時

 String notfound="<html><head><title>

Not Found</title></head>

 <body><hl>Error404-File notfound

</hl></body></html>";

 outstream.println("HTTP /1.0 404 no found");

 outstream.println("Content_Type:text /html");

 outstream.println

("Content_Length:" +notfound.length() +2);

 outstream.println("");

 outstream.println(notfound);

 outstream.flush();

 }

 }

 long m1=1;

 while(m10)

 {

 if(s.substring(0,3).equalsIgnoreCase

("GET"))return true;

 }

 return false;

 }

 /*擷取要訪問的檔案名稱*/

 String getfilename(String s){

 String f=s.substring(s.indexOf('')+1);

 f=f.substring(0,f.indexOf(''));

 try{

 if(f.charAt(0)=='/')

 f=f.substring(1);

 }catch(String IndexOutOfBoundsException e){

 System.out.println("Exception:"+e);

 }

 if(f.equals(""))f="index.html";

 return f;

 }

 /*把指定檔案發送給Web瀏覽器*/

 void sendfile(PrintStream outs,File file){

 try{

 DataInputStreamin=new DataInputStream

(new FileInputStream(file));

 int len=(int)file.length();

 byte buf[]=new byte[len];

 in.readFully(buf);

 outs.write(buf,0,len);

 outs.flush();

 in.close();

 }catch(Exception e){

 System.out.println("Error retrieving file.");

 System.exit(1);

 }

 }

 }

  程式中的Connection Thread線程子類用來分析一個Web瀏覽器提交的請求,並將應答資訊傳回給Web瀏覽器。其中,getrequest()方法用來檢測客戶的請求是否為"GET";getfilename(s)方法是從客戶請求資訊s中擷取要訪問的HTML檔案名稱;sendfile()方法把指定檔案內容通過socket傳回給Web瀏覽器。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.