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.print("

Directory of ");

pw.print(req);

pw.println("

File[] contents = dir.listFiles();

for (int i = 0; i < contents.length; i++) {

pw.print("

");

pw.print("

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("

");

pw.println("

");

}

pw.println("

");

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);

}

}

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

java webserver demo_Java 实现 web服务器的简单实例相关推荐

  1. js调用java_Js调用Java方法并互相传参的简单实例

    Js通过PhoneGap调用Java方法并互相传参的. 一.JAVA代码 写一个类,该类继承自Plugin并重写execute方法. public class PluginTest extends P ...

  2. js调java并传参_Js调用Java方法并互相传参的简单实例

    Js通过PhoneGap调用Java方法并互相传参的. 一.JAVA代码 写一个类,该类继承自Plugin并重写execute方法. import org.json.JSONArray; import ...

  3. Java程序如何写判断闰年_用Java程序判断是否是闰年的简单实例

    我们知道,(1)如果是整百的年份,能被400整除的,是闰年:(2)如果不是整百的年份,能被4整除的,也是闰年.每400年,有97个闰年.鉴于此,程序可以作以下设计: 第一步,判断年份是否被400整除, ...

  4. java数字编程提,java从字符串中提取数字的简单实例

    随便给你一个含有数字的字符串,比如: String s="eert343dfg56756dtry66fggg89dfgf"; 那我们怎么把其中的数字提取出来呢?大致有以下几种方法, ...

  5. 编写java判断闰年_用Java程序判断是否是闰年的简单实例

    我们知道,(1)如果是整百的年份,能被400整除的,是闰年:(2)如果不是整百的年份,能被4整除的,也是闰年.每400年,有97个闰年.鉴于此,程序可以作以下设计: 第一步,判断年份是否被400整除, ...

  6. web服务器的简单实现——HTTP权威指南读书心得(七)

    我又回来做笔记了~最近懒死了,书虽然看完了,但是一直懒得动笔,这样不行啊(¯﹃¯)口水.还有在这里吐槽下,在围观这本书的时候,一直有一种奇怪的感觉:里面说的有些东西与时代脱节啊......越读越感觉不 ...

  7. JAVA实现支持视频点播WEB服务器

    一.项目简介: JAVA语言是一种可移植的,简单的,健壮的嵌入式语言.并且对网络,数据库有很好的支持,基于JAVA语言的这种特性可以十分容易地建立一个小型INTERNET服务器. 本项目中,作者用JA ...

  8. 用JAVA实现对视频点播WEB服务器的支持

    JAVA语言是一种可移植的,简单的,健壮的嵌入式语言.并且对网络,数据库有很好的支持,基于JAVA语言的这种特性可以十分容易地建立一个小型INTERNET服务器. 本项目中,用JAVA语言编写了一个W ...

  9. web服务器php配置实例,配置 Web 服务器提供 PHP 服务

    有多种方式来配置一个 web 服务器以提供 PHP 服务.传统(并且糟糕的)的方式是使用 Apache 的 mod_php.Mod_php将PHP 绑定到 Apache 自身,但是 Apache 对于 ...

最新文章

  1. Unity* 实体组件系统 (ECS)、C# 作业系统和突发编译器入门
  2. 如何用手机打开dcm格式图片_手机也能当扫描仪用?如何用手机扫描图片?
  3. python笔记-列表和元组
  4. Java设计模式(学习整理)---单例模式
  5. 因OpenCV版本不一致所引发的报错
  6. 【NOIP2017】逛公园【最短路DAG】【dp】【拓扑排序】
  7. ALSA音频工具amixer,aplay,arecord
  8. js部分---表单验证;(含正则表达式)
  9. 【转】缺陷与出路—一个游戏开发者的反思
  10. wrong ELF class: ELFCLASS64
  11. java中sql查找_Java 中如何使用 SQL 查询文本
  12. 数据结构以及相关排序
  13. 聊天机器人闲聊语料 - 1
  14. android自定义速度仪表盘,自定义View实战:汽车速度仪表盘
  15. 正态分布的峰度和偏度分别为_关于偏度与峰度的一些探索
  16. 2018携程实习生大数据分析笔试练习题
  17. Logstash:日志解析的 Grok 模式示例
  18. 嵌入式Uboot,通过tftp进行内核镜像的加载及flash写入
  19. 什么是软件测试及其分类?
  20. DirectShow编程(3.5) - 关于DirectShow - DirectShow中的事件通告

热门文章

  1. Ubuntu之systemd延时启动服务
  2. OpenSL ES录音流程(一)
  3. Mac otool替代readelf命令
  4. Android -- 无线网络配置信息的管理者WifiConfigStore简介
  5. windows清除记住的密码
  6. wpf之代码设置背景图片
  7. LED显示驱动(二):显示驱动FPGA验证流程与注意细节
  8. Python报错:module ‘turtle’ has no attribute ‘pensize’
  9. cesium加载 gltf模型
  10. python樱桃小丸子_appium+python自动化框架搭建