热门标签 | HotTags
当前位置:  开发笔记 > 前端 > 正文

Java实现web服务器的简单实例

这篇文章主要介绍了Java实现web服务器的简单实例的相关资料,需要的朋友可以参考下

Java 实现 web服务器的简单实例

实例代码:

import java.util.*; 
 
// Chapter 8, Listing 3 
public class WebServerDemo { 
  // Directory of HTML pages and other files 
  protected String docroot; 
  // Port number of web server 
  protected int port; 
  // Socket for the web server 
  protected ServerSocket ss; 
 
  // Handler for a HTTP request 
  class Handler extends Thread { 
    protected Socket socket; 
    protected PrintWriter pw; 
    protected BufferedOutputStream bos; 
    protected BufferedReader br; 
    protected File docroot; 
 
    public Handler(Socket _socket, String _docroot) throws Exception { 
      socket = _socket; 
      // Get the absolute directory of the filepath 
      docroot = new File(_docroot).getCanonicalFile(); 
    } 
 
    public void run() { 
      try { 
        // Prepare our readers and writers 
        br = new BufferedReader(new InputStreamReader( 
            socket.getInputStream())); 
        bos = new BufferedOutputStream(socket.getOutputStream()); 
        pw = new PrintWriter(new OutputStreamWriter(bos)); 
 
        // Read HTTP request from user (hopefully GET /file...... ) 
        String line = br.readLine(); 
 
        // Shutdown any further input 
        socket.shutdownInput(); 
 
        if (line == null) { 
          socket.close(); 
          return; 
        } 
        if (line.toUpperCase().startsWith("GET")) { 
          // Eliminate any trailing ? data, such as for a CGI GET 
          // request 
          StringTokenizer tokens = new StringTokenizer(line, " ?"); 
          tokens.nextToken(); 
          String req = tokens.nextToken(); 
 
          // If a path character / or / is not present, add it to the 
          // document root 
          // and then add the file request, to form a full filename 
          String name; 
          if (req.startsWith("/") || req.startsWith("//")) 
            name = this.docroot + req; 
          else 
            name = this.docroot + File.separator + req; 
 
          // Get absolute file path 
          File file = new File(name).getCanonicalFile(); 
 
          // Check to see if request doesn't start with our document 
          // root .... 
          if (!file.getAbsolutePath().startsWith( 
              this.docroot.getAbsolutePath())) { 
            pw.println("HTTP/1.0 403 Forbidden"); 
            pw.println(); 
          } 
          // ... if it's missing ..... 
          else if (!file.exists()) { 
            pw.println("HTTP/1.0 404 File Not Found"); 
            pw.println(); 
          } 
          // ... if it can't be read for security reasons .... 
          else if (!file.canRead()) { 
            pw.println("HTTP/1.0 403 Forbidden"); 
            pw.println(); 
          } 
          // ... if its actually a directory, and not a file .... 
          else if (file.isDirectory()) { 
            sendDir(bos, pw, file, req); 
          } 
          // ... or if it's really a file 
          else { 
            sendFile(bos, pw, file.getAbsolutePath()); 
          } 
        } 
        // If not a GET request, the server will not support it 
        else { 
          pw.println("HTTP/1.0 501 Not Implemented"); 
          pw.println(); 
        } 
 
        pw.flush(); 
        bos.flush(); 
      } catch (Exception e) { 
        e.printStackTrace(); 
      } 
      try { 
        socket.close(); 
      } catch (Exception e) { 
        e.printStackTrace(); 
      } 
    } 
 
    protected void sendFile(BufferedOutputStream bos, PrintWriter pw, 
        String filename) throws Exception { 
      try { 
        java.io.BufferedInputStream bis = new java.io.BufferedInputStream( 
            new FileInputStream(filename)); 
        byte[] data = new byte[10 * 1024]; 
        int read = bis.read(data); 
 
        pw.println("HTTP/1.0 200 Okay"); 
        pw.println(); 
        pw.flush(); 
        bos.flush(); 
 
        while (read != -1) { 
          bos.write(data, 0, read); 
          read = bis.read(data); 
        } 
        bos.flush(); 
      } catch (Exception e) { 
        pw.flush(); 
        bos.flush(); 
      } 
    } 
 
    protected void sendDir(BufferedOutputStream bos, PrintWriter pw, 
        File dir, String req) throws Exception { 
      try { 
        pw.println("HTTP/1.0 200 Okay"); 
        pw.println(); 
        pw.flush(); 
 
        pw.print("

Directory of "); pw.print(req); pw.println("

"); File[] cOntents= dir.listFiles(); for (int i = 0; i "); pw.print(""); pw.println(""); } pw.println("
"); if (contents[i].isDirectory()) pw.print("Dir -> "); pw.print(contents[i].getName()); pw.print("
"); pw.flush(); } catch (Exception e) { pw.flush(); bos.flush(); } } } // Check that a filepath has been specified and a port number protected void parseParams(String[] args) throws Exception { switch (args.length) { case 1: case 0: System.err.println("Syntax: " + this.getClass().getName() + " docroot port"); System.exit(0); default: this.docroot = args[0]; this.port = Integer.parseInt(args[1]); break; } } public WebServerDemo(String[] args) throws Exception { System.out.println("Checking for paramters"); // Check for command line parameters parseParams(args); System.out.print("Starting web server...... "); // Create a new server socket this.ss = new ServerSocket(this.port); System.out.println("OK"); for (;;) { // Accept a new socket connection from our server socket Socket accept = ss.accept(); // Start a new handler instance to process the request new Handler(accept, docroot).start(); } } // Start an instance of the web server running public static void main(String[] args) throws Exception { WebServerDemo webServerDemo = new WebServerDemo(args); } }

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!


推荐阅读
  • 如何实现织梦DedeCms全站伪静态
    本文介绍了如何通过修改织梦DedeCms源代码来实现全站伪静态,以提高管理和SEO效果。全站伪静态可以避免重复URL的问题,同时通过使用mod_rewrite伪静态模块和.htaccess正则表达式,可以更好地适应搜索引擎的需求。文章还提到了一些相关的技术和工具,如Ubuntu、qt编程、tomcat端口、爬虫、php request根目录等。 ... [详细]
  • Nginx使用AWStats日志分析的步骤及注意事项
    本文介绍了在Centos7操作系统上使用Nginx和AWStats进行日志分析的步骤和注意事项。通过AWStats可以统计网站的访问量、IP地址、操作系统、浏览器等信息,并提供精确到每月、每日、每小时的数据。在部署AWStats之前需要确认服务器上已经安装了Perl环境,并进行DNS解析。 ... [详细]
  • 本文介绍了在开发Android新闻App时,搭建本地服务器的步骤。通过使用XAMPP软件,可以一键式搭建起开发环境,包括Apache、MySQL、PHP、PERL。在本地服务器上新建数据库和表,并设置相应的属性。最后,给出了创建new表的SQL语句。这个教程适合初学者参考。 ... [详细]
  • 这是原文链接:sendingformdata许多情况下,我们使用表单发送数据到服务器。服务器处理数据并返回响应给用户。这看起来很简单,但是 ... [详细]
  • 本文介绍了使用AJAX的POST请求实现数据修改功能的方法。通过ajax-post技术,可以实现在输入某个id后,通过ajax技术调用post.jsp修改具有该id记录的姓名的值。文章还提到了AJAX的概念和作用,以及使用async参数和open()方法的注意事项。同时强调了不推荐使用async=false的情况,并解释了JavaScript等待服务器响应的机制。 ... [详细]
  • 本文介绍了求解gcdexgcd斐蜀定理的迭代法和递归法,并解释了exgcd的概念和应用。exgcd是指对于不完全为0的非负整数a和b,gcd(a,b)表示a和b的最大公约数,必然存在整数对x和y,使得gcd(a,b)=ax+by。此外,本文还给出了相应的代码示例。 ... [详细]
  • VScode格式化文档换行或不换行的设置方法
    本文介绍了在VScode中设置格式化文档换行或不换行的方法,包括使用插件和修改settings.json文件的内容。详细步骤为:找到settings.json文件,将其中的代码替换为指定的代码。 ... [详细]
  • Nginx使用(server参数配置)
    本文介绍了Nginx的使用,重点讲解了server参数配置,包括端口号、主机名、根目录等内容。同时,还介绍了Nginx的反向代理功能。 ... [详细]
  • 基于layUI的图片上传前预览功能的2种实现方式
    本文介绍了基于layUI的图片上传前预览功能的两种实现方式:一种是使用blob+FileReader,另一种是使用layUI自带的参数。通过选择文件后点击文件名,在页面中间弹窗内预览图片。其中,layUI自带的参数实现了图片预览功能。该功能依赖于layUI的上传模块,并使用了blob和FileReader来读取本地文件并获取图像的base64编码。点击文件名时会执行See()函数。摘要长度为169字。 ... [详细]
  • 电销机器人作为一种人工智能技术载体,可以帮助企业提升电销效率并节省人工成本。然而,电销机器人市场缺乏统一的市场准入标准,产品品质良莠不齐。创业者在代理或购买电销机器人时应注意谨防用录音冒充真人语音通话以及宣传技术与实际效果不符的情况。选择电销机器人时需要考察公司资质和产品品质,尤其要关注语音识别率。 ... [详细]
  • 如何去除Win7快捷方式的箭头
    本文介绍了如何去除Win7快捷方式的箭头的方法,通过生成一个透明的ico图标并将其命名为Empty.ico,将图标复制到windows目录下,并导入注册表,即可去除箭头。这样做可以改善默认快捷方式的外观,提升桌面整洁度。 ... [详细]
  • 本文介绍了数据库的存储结构及其重要性,强调了关系数据库范例中将逻辑存储与物理存储分开的必要性。通过逻辑结构和物理结构的分离,可以实现对物理存储的重新组织和数据库的迁移,而应用程序不会察觉到任何更改。文章还展示了Oracle数据库的逻辑结构和物理结构,并介绍了表空间的概念和作用。 ... [详细]
  • Java实战之电影在线观看系统的实现
    本文介绍了Java实战之电影在线观看系统的实现过程。首先对项目进行了简述,然后展示了系统的效果图。接着介绍了系统的核心代码,包括后台用户管理控制器、电影管理控制器和前台电影控制器。最后对项目的环境配置和使用的技术进行了说明,包括JSP、Spring、SpringMVC、MyBatis、html、css、JavaScript、JQuery、Ajax、layui和maven等。 ... [详细]
  • 本文介绍了使用Java实现大数乘法的分治算法,包括输入数据的处理、普通大数乘法的结果和Karatsuba大数乘法的结果。通过改变long类型可以适应不同范围的大数乘法计算。 ... [详细]
  • Webpack5内置处理图片资源的配置方法
    本文介绍了在Webpack5中处理图片资源的配置方法。在Webpack4中,我们需要使用file-loader和url-loader来处理图片资源,但是在Webpack5中,这两个Loader的功能已经被内置到Webpack中,我们只需要简单配置即可实现图片资源的处理。本文还介绍了一些常用的配置方法,如匹配不同类型的图片文件、设置输出路径等。通过本文的学习,读者可以快速掌握Webpack5处理图片资源的方法。 ... [详细]
author-avatar
l38484676
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有