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

发布时间 - 2026-01-11 01:57:18    点击率:

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("<html><head><title>Directory of "); 
        pw.print(req); 
        pw.print("</title></head><body><h1>Directory of "); 
        pw.print(req); 
        pw.println("</h1><table border=/"0/">"); 
 
        File[] contents = dir.listFiles(); 
 
        for (int i = 0; i < contents.length; i++) { 
          pw.print("<tr>"); 
          pw.print("<td><a href="/" rel="external nofollow" rel="external nofollow" mce_href="/" rel="external nofollow" rel="external nofollow" ""); 
          pw.print(req); 
          pw.print(contents[i].getName()); 
          if (contents[i].isDirectory()) 
            pw.print("/"); 
          pw.print("/">"); 
          if (contents[i].isDirectory()) 
            pw.print("Dir -> "); 
          pw.print(contents[i].getName()); 
          pw.print("</a></td>"); 
          pw.println("</tr>"); 
        } 
        pw.println("</table></body></html>"); 
        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: <jvm> " + 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); 
  } 
} 

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


# Java  # 实现  # web服务器  # web服务器的实例  # java实现一个简单的Web服务器实例解析  # java 与web服务器链接的实例  # AngularJS实现与Java Web服务器交互操作示例【附demo源码下载】  # 基于Java web服务器简单实现一个Servlet容器  # 简单实现Java web服务器  # Java实现简易Web服务器  # Java中常见的5种WEB服务器介绍  # Java Socket编程(五) 简单的WEB服务器  # 搭建JavaWeb服务器步骤详解  # 希望能  # 谢谢大家  # Read  # user  # OutputStreamWriter  # getInputStream  # getOutputStream  # file  # input  # shutdownInput  # Shutdown  # line  # readLine  # filepath  # getCanonicalFile  # directory  # Exception  # absolute  # void  # writers 


相关栏目: 【 网站优化151355 】 【 网络推广146373 】 【 网络技术251813 】 【 AI营销90571


相关推荐: 详解ASP.NET 生成二维码实例(采用ThoughtWorks.QRCode和QrCode.Net两种方式)  如何在IIS中新建站点并配置端口与物理路径?  如何挑选高效建站主机与优质域名?  Laravel如何发送系统通知_Laravel Notifications实现多渠道消息通知  晋江文学城电脑版官网 晋江文学城网页版直接进入  php结合redis实现高并发下的抢购、秒杀功能的实例  什么是javascript作用域_全局和局部作用域有什么区别?  如何用手机制作网站和网页,手机移动端的网站能制作成中英双语的吗?  标题:Vue + Vuex + JWT 身份认证的正确实践与常见误区解析  PHP怎么接收前端传的文件路径_处理文件路径参数接收方法【汇总】  Laravel怎么进行数据库回滚_Laravel Migration数据库版本控制与回滚操作  html如何与html链接_实现多个HTML页面互相链接【互相】  edge浏览器无法安装扩展 edge浏览器插件安装失败【解决方法】  黑客如何利用漏洞与弱口令入侵网站服务器?  JavaScript如何实现错误处理_try...catch如何捕获异常?  bootstrap日历插件datetimepicker使用方法  简单实现Android验证码  如何构建满足综合性能需求的优质建站方案?  Linux系统命令中screen命令详解  魔方云NAT建站如何实现端口转发?  zabbix利用python脚本发送报警邮件的方法  Laravel如何与Inertia.js和Vue/React构建现代单页应用  BootStrap整体框架之基础布局组件  哪家制作企业网站好,开办像阿里巴巴那样的网络公司和网站要怎么做?  Python文件异常处理策略_健壮性说明【指导】  如何在IIS7上新建站点并设置安全权限?  Laravel如何连接多个数据库_Laravel多数据库连接配置与切换教程  Laravel怎么实现微信登录_Laravel Socialite第三方登录集成  如何自定义建站之星网站的导航菜单样式?  Laravel如何发送邮件和通知_Laravel邮件与通知系统发送步骤  微信小程序 配置文件详细介绍  Laravel安装步骤详细教程_Laravel环境搭建指南  详解Huffman编码算法之Java实现  如何使用 jQuery 正确渲染 Instagram 风格的标签列表  php 三元运算符实例详细介绍  Windows10如何更改计算机工作组_Win10系统属性修改Workgroup  Laravel如何使用withoutEvents方法临时禁用模型事件  Laravel如何集成第三方登录_Laravel Socialite实现微信QQ微博登录  Laravel Session怎么存储_Laravel Session驱动配置详解  Laravel如何安装使用Debugbar工具栏_Laravel性能调试与SQL监控插件【步骤】  谷歌浏览器下载文件时中断怎么办 Google Chrome下载管理修复  如何在建站之星网店版论坛获取技术支持?  浅述节点的创建及常见功能的实现  Laravel如何使用Gate和Policy进行权限控制_Laravel权限判定与策略规则配置  如何快速搭建个人网站并优化SEO?  通义万相免费版怎么用_通义万相免费版使用方法详细指南【教程】  Laravel项目如何进行性能优化_Laravel应用性能分析与优化技巧大全  Laravel如何实现本地化和多语言支持_Laravel多语言配置与翻译文件管理  微信小程序 scroll-view组件实现列表页实例代码  香港服务器WordPress建站指南:SEO优化与高效部署策略