Java 实现简易Web服务器

本文介绍了一个用Java编写的简易HTTP服务器实现,该服务器能够处理基本的HTTP请求,并根据请求资源类型返回相应的静态文件,如HTML、CSS、JavaScript、图片等。服务器通过参数配置端口、主页和本地路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.io.*;
import java.net.*;
import java.util.*;

public class j8httpServer {
  private static char cPort = 8888;
  private static final String sVersion = "j8httpServer/1.0(JVM)";
  private static String sHomePage = "index.html";
  private static String sLocalPath = "wwwroot";

  public static void main(String[] sa) {
    getArgument(sa);
    ServerSocket ss = null;

    try {
      ss = new ServerSocket(cPort);
      System.out.println(sVersion + " m@20190429.yiyi");
      while(true) {
        Socket s = ss.accept();
        BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
        String sLine = br.readLine();
        doSwitch(s, sLine.substring(sLine.indexOf('/') + 1, sLine.lastIndexOf('/') - 5));
        br.close();
        s.close();
      }
    } catch(Exception e) {
      e.printStackTrace();
    }
  }

  private static void doSwitch(Socket s, String sResource) throws Exception {
    if(sResource.equals("")) {
      sResource = sHomePage;
    }

    if(sResource.toLowerCase().endsWith(".css")) {
      toTransfer(s, "text/css", sResource);
    } else if(sResource.toLowerCase().endsWith(".html") || sResource.toLowerCase().endsWith(".htm")) {
      toTransfer(s, "text/html", sResource);
    } else if(sResource.toLowerCase().endsWith(".js")) {
      toTransfer(s, "text/javascript", sResource);
    } else if(sResource.toLowerCase().endsWith(".gif")) {
      toTransfer(s, "image/gif", sResource);
    } else if(sResource.toLowerCase().endsWith(".jpeg") || sResource.toLowerCase().endsWith(".jpg")) {
      toTransfer(s, "image/jpeg", sResource);
    } else if(sResource.toLowerCase().endsWith(".png")) {
      toTransfer(s, "image/png", sResource);
    } else {
      notFound(s);
    }
  }

  private static void getArgument(String[] sa) {
    try {
      for(int i = 0; i < sa.length; i++) {
        if(sa[i].toLowerCase().startsWith("-port:")) {
          int iPort = Integer.valueOf(sa[i].substring(6));
          if(iPort >= 0 && iPort < 65536) {
            cPort = (char)iPort;
          }
        } else if(sa[i].toLowerCase().startsWith("-homepage:")) {
          sHomePage = sa[i].substring(10);
        } else if(sa[i].toLowerCase().startsWith("-localpath:")) {
          sLocalPath = sa[i].substring(11);
        }
      }
    } catch(NumberFormatException nfe) {
      nfe.printStackTrace();
    }
  }

  private static void notFound(Socket s) throws Exception {
    PrintWriter pw = new PrintWriter(s.getOutputStream());
    pw.println("HTTP/1.0 404 Not found");
    pw.println("Server:" + sVersion);
    pw.println("Date:" + new Date());
    pw.println();
    pw.flush();
    pw.close();
  }

  private static void toTransfer(Socket s, String sContentType, String sRemotePath) throws Exception {
    PrintStream ps = new PrintStream(s.getOutputStream());
    File f = new File(sLocalPath + File.separator + sRemotePath);
    Long l = f.length();
    byte[] b = new byte[l.intValue()];

    ps.println("HTTP/1.1 200 OK");
    ps.println("Content-Type:" + sContentType);
    ps.println("Content-Length:" + l);
    ps.println("Server:" + sVersion);
    ps.println("Date:" + new Date());
    ps.println();

    FileInputStream fis = new FileInputStream(f);
    fis.read(b);
    fis.close();

    if(sContentType.startsWith("text/")) {
      ps.print(new String(b));
    } else {
      ps.write(b);
    }

    ps.flush();
    ps.close();
  }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值