中学生作文 语文教案 高考作文 文言文翻译 新课程改革 说课稿 诗歌散文欣赏 中考高考应考对策 语文教学论文之二 语文教学论文之三
语文教学论文之四 小学语文论文 小学语教案文 小学语文试题 小学生园地 文学欣赏 小学教师园地 小学语文课件 语文试题 数学试题
化学试题
物理试题 历史试题 政治试题 英语试题 生物试题 地理试题 其它教案 语文教案 数学教案 化学教案 物理教案
历史教案 政治教案 英语教案 生物教案 地理教案

HomeArticle        > IT培训      

> 用Java实现Web服务器


  文章内容
 


用Java实现Web服务器


 
 

  超文本传输协议(HTTP)是位于TCP/IP 协议的应用层,是最广为人知的协议,也是互连网中最核心的协议之一,同样,HTTP 也是基于 C/S 或 B/S 模型实现的。事实上,我们使用的浏览器如Netscape 或IE 是实现HTTP 协议中的客户端,而一些常用的Web 服务器软件如Apache、IIS 和iPlanet Web Server 等是实现HTTP 协议中的服务器端。Web 页由服务端资源定位,传输到浏览器,经过浏览器的解释后,被客户所看到。

  Web 的工作基于客户机/服务器计算模型,由Web 浏览器(客户机)和Web服务器(服务器)构成,两者之间采用超文本传送协议(HTTP)进行通信。HTTP协议是Web浏览器和Web服务器之间的应用层协议,是通用的、无状态的、面向对象的协议。

  一个完整的HTTP协议会话过程包括四个步骤:

  ◆ 连接,Web浏览器与Web服务器建立连接,打开一个称为Socket(套接字)的虚拟文件,此文件的建立标志着连接建立成功;

  ◆ 请求,Web浏览器通过Socket向Web服务器提交请求。HTTP的请求一般是GET或POST命令(POST用于FORM参数的传递);

  ◆ 应答,Web浏览器提交请求后,通过HTTP协议传送给Web服务器。Web服务器接到后,进行事务处理,处理结果又通过HTTP传回给Web浏览器,从而在Web浏览器上显示出所请求的页面;

  ◆ 关闭连接,应答结束后Web浏览器与Web服务器必须断开,以保证其它Web浏览器能够与Web服务器建立连接。

 

Java实现Web服务器功能的程序设计

  编程思路

  根据上述HTTP协议的会话过程,本实例中实现了GET请求的Web服务器程序的方法,方法如下:

  通过创建ServerSocket 类对象,侦听用户指定的端口(为8080),等待并接受客户机请求到端口。创建与Socket相关联的输入流和输出流,然后读取客户机的请求信息。若请求类型是GET,则从请求信息中获取所访问的HTML 文件名;如果HTML 文件存在,则打开HTML 文件,把HTTP 头信息和HTML 文件内容通过Socket 传回给Web浏览器,然后关闭文件,否则发送错误信息给Web 浏览器。最后关闭与相应Web 浏览器连接的Socket。
用Java编写Web服务器httpServer.java文件的源代码如下:


//httpServer.java import java.net.*;import java.io.*;import java.util.*;import java.lang.*;public class httpServer{    public static void main(String args[]) { int port; ServerSocket server_socket;        //读取服务器端口号 try {            port = Integer.parseInt(args[0]); } catch (Exception e) {     port = 8080; } try {            //监听服务器端口,等待连接请求     server_socket = new ServerSocket(port);     System.out.println(httpServer running on port +         server_socket.getLocalPort());     //显示启动信息     while(true) {  Socket socket = server_socket.accept();  System.out.println(New connection accepted +       socket.getInetAddress() +       : + socket.getPort());  //创建分线程  try {      httpRequestHandler request =   new httpRequestHandler(socket);         Thread thread = new Thread(request);      //启动线程      thread.start();  }  catch(Exception e) {      System.out.println(e);  }     } } catch (IOException e) {     System.out.println(e); }    }}class httpRequestHandler implements Runnable{    final static String CRLF = \r\n;    Socket socket;    InputStream input;    OutputStream output;    BufferedReader br;    // 构造方法    public httpRequestHandler(Socket socket) throws Exception    { this.socket = socket; this.input = socket.getInputStream(); this.output = socket.getOutputStream(); this.br =     new BufferedReader(new InputStreamReader(socket.getInputStream()));    }    // 实现Runnable 接口的run()方法    public void run()    { try {     processRequest(); } catch(Exception e) {     System.out.println(e); }    }    private void processRequest() throws Exception    { while(true) {            //读取并显示Web 浏览器提交的请求信息     String headerLine = br.readLine();     System.out.println(The client request is +headerLine);     if(headerLine.equals(CRLF) || headerLine.equals()) break;     StringTokenizer s = new StringTokenizer(headerLine);     String temp = s.nextToken();     if(temp.equals(GET)) {  String fileName = s.nextToken();  fileName = . + fileName ;  // 打开所请求的文件  FileInputStream fis = null ;  boolean fileExists = true ;  try      {   fis = new FileInputStream( fileName ) ;      }  catch ( FileNotFoundException e )      {   fileExists = false ;      }  // 完成回应消息  String serverLine = Server: a simple java httpServer;  String statusLine = null;  String contentTypeLine = null;  String entityBody = null;  String contentLengthLine = error;  if ( fileExists )      {   statusLine = HTTP/1.0 200 OK + CRLF ;   contentTypeLine = Content-type: +       contentType( fileName ) + CRLF ;   contentLengthLine = Content-Length:        + (new Integer(fis.available())).toString()       + CRLF;      }  else      {   statusLine = HTTP/1.0 404 Not Found + CRLF ;   contentTypeLine = text/html ;   entityBody = <HTML> +       <HEAD><TITLE>404 Not Found</TITLE></HEAD> +       <BODY>404 Not Found       +<br>usage:http://yourHostName:port/       +fileName.html</BODY></HTML> ;      }  // 发送到服务器信息  output.write(statusLine.getBytes());  output.write(serverLine.getBytes());  output.write(contentTypeLine.getBytes());  output.write(contentLengthLine.getBytes());               output.write(CRLF.getBytes());  // 发送信息内容  if (fileExists)      {   sendBytes(fis, output) ;   fis.      }  else      {   output.write(entityBody.getBytes());      }     } }        //关闭套接字和流 try {     output.     br.     socket. } catch(Exception e) {}    }    private static void sendBytes(FileInputStream fis, OutputStream os) throws Exception    { // 创建一个 1K buffer byte[] buffer = new byte[1024] ; int bytes = 0 ; // 将文件输出到套接字输出流中 while ((bytes = fis.read(buffer)) != -1 )     {  os.write(buffer, 0, bytes);     }    }    private static String contentType(String fileName)    { if (fileName.endsWith(.htm) || fileName.endsWith(.html))     {  return text/html;     } return fileName;    }}
 
编程技巧说明

  ◆ 主线程设计

  主线程的设计就是在主线程httpServer 类中实现了服务器端口的侦听,服务器接受一个客户端请求之后创建一个线程实例处理请求,代码如下:


import java.net.*;import java.io.*;import java.util.*;import java.lang.*;public class httpServer{ public static void main(String args[]) {  port;   ServerSocket server_socket;   //读取服务器端口号   try {    port = Integer.parseInt(args[0]);   }   catch (Exception e) {    port = 8080;   }   try {    //监听服务器端口,等待连接请求    server_socket = new ServerSocket(port);    System.out.println(httpServer running on port +server_socket.getLocalPort());    ..........    ..........
 

 

  ◆ 连接处理分线程设计

  在分线程httpRequestHandler 类中实现了HTTP 协议的处理,这个类实现了Runnable 接口,代码如下:


class httpRequestHandler implements Runnable
{
    final static String CRLF = \r\n;
    Socket socket;
    InputStream input;
    OutputStream output;
    BufferedReader br;
    // 构造方法
    public httpRequestHandler(Socket socket) throws Exception
    {
 this.socket = socket;
 //得到输入输出流
        this.input = socket.getInputStream();
 this.output = socket.getOutputStream();
 this.br =
     new BufferedReader(new InputStreamReader(socket.getInputStream()));
    }
    // 实现Runnable 接口的run()方法
    public void run()
    {
 try {
     processRequest();
 }
 catch(Exception e) {
     System.out.println(e);
 }
    }

 

  ◆ 构建processRequest()方法来处理信息的接收和发送

  作为实现Runnable 接口的主要内容,在run()方法中调用processRequest()方法来处理客户请求内容的接收和服务器返回信息的发送,代码如下:


private void processRequest() throws Exception
 {
 while(true) {
  //读取并显示Web 浏览器提交的请求信息
  String headerLine = br.readLine();
  System.out.println(The client request is + headerLine);
  if(headerLine.equals(CRLF) || headerLine.equals()) break;
  //根据请求字符串中的空格拆分客户请求
  StringTokenizer s = new StringTokenizer(headerLine);
  String temp = s.nextToken();
  if(temp.equals(GET)) {
  String fileName = s.nextToken();
  fileName = . + fileName ;
   .............
  .............


  在processRequest()方法中得到客户端请求后,利用一个StringTokenizer 类完成了字符串的拆分,这个类可以实现根据字符串中指定的分隔符(缺省为空格)将字符串拆分成为字串的功能。利用nextToken()方法依次得到这些字串;sendBytes()方法完成信息内容的发送,contentType()方法用于判断文件的类型。

  显示Web页面

  显示 Web 页面的index.html 文件代码如下:


<html>
<head>
<meta http-equiv=Content-Language content=zh-cn>
<meta name=GENERATOR content=Microsoft FrontPage 5.0>
<meta http-equiv=Content-Type content=text/html; charset=gb2312>
<title>Java Web 服务器</title>
</head>
<body>
<p>********* <font color=#FF0000>欢迎你的到来!</font>*********</p>
<p>这是一个用 Java 语言实现的 Web 服务器</p>
<hr>
</body>
</html>

 


  运行实例

  为了测试上述程序的正确性,将编译后的httpServer.class、httpRequestHandler.class和上面的index.html文件置于网络的某台主机的同一目录中。

  首先运行服务器程序 java httpServer 8080,服务器程序运行后显示端口信息“httpServer runing on port 8080”, 然后在浏览器的地址栏中输入http://localhost:8080/index.html,就可以正确显示网页,同时在显示“httpServer runing on port 8080 ”窗口中服务器会出现一些信息。

 
State

学科试题测试
教学知识小品
教学心得随笔之一
教育教学论文
教学设计教案
教学心得随笔之二
教学心得随笔之三
工科论文
管理学论文
公共管理论文
经济学论文
法律论文
政治学论文
会计审计论文
艺术论文
其它类论文
证券金融论文
论文指导
财政税收论文
工商管理论文
财务管理论文
计算机论文
医学论文
哲学论文
教育论文
少儿英语
综合英语
考研&MBA
国内考试
企业法律顾问
小语种
出国考试
学习顾问
IT培训
管理培训
商务英语
会计考试
英语考试
司法考试
英语口语
导游员考试
自学考试
公务员考试
报关员考试
CET考试综合信息
CET四级考试
CET六级考试
PETS考试
等级考试综合信息
计算机等级一级考试
计算机等级二级考试
计算机等级三级考试
计算机等级四级考试
全国计算机NIT考试
软考试综合信息
数据库系统工程师
网络管理(程序)员
程序员级
网络设计师
软件设计师(高程)
系统分析师
 


Copyright www.schoolscn.com All rights reserved. ICP备05047758号