简单Web服务器
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URLDecoder;
import java.util.StringTokenizer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; /**
* 用Java语言实现HTTP服务器,首先启动一个java.net.ServerSocket在提供服务的端口上监听连接.向客户返回文本时,可以用
* PrintWriter,但是如果返回二进制数据,则必须使用OutputStream.write(byte[])方法,返回的应答消息字符串可以使用
* String.getBytes()方法转换为字节数组返回,或者使用PrintStream的print()方法写入文本,用
* write(byte[])方法写入二进制数据.
*
* 以工程所在目录为web的根目录。 在工程的根目录下放一个大概如下的index.html
*
* <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
* "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta
* http-equiv="Content-Type" content="text/html; charset=gbk">
* <title>简单的测试</title> </head> <body> 你好!这是一个 简单的web服务器。<br>
* 这是一个图片!<br>
*
* <form action="/index.html"> <img alt="" src="data:images/test.gif"><br>
* 姓名:<input type="text" name="name" /><br>
* 密码:<input type="password" name="pass"></input><br>
* <input type="submit"/> </form> </body> </html>
*
* 放入图片位置: 工程根目录/images/test.gif <br>
* 打开浏览器输入http://localhost/index.html 可以展示index.html
*
* @author rommel1
*/
public class SimpleHttpServer { ServerSocket serverSocket;// 服务器Socket
ExecutorService pool = Executors.newFixedThreadPool(2); /**
* 服务器监听端口, 默认为 80.
*/
public static int PORT = 80;// 标准HTTP端口 /**
* 开始服务器 Socket 线程.
*/
public SimpleHttpServer() {
try {
serverSocket = new ServerSocket(PORT);
} catch (Exception e) {
System.out.println("无法启动HTTP服务器:" + e.getMessage());
}
if (serverSocket == null)
System.exit(1);// 无法开始服务器 // new Thread(this).start();
System.out.println("HTTP服务器正在运行,端口:" + PORT);
while (true) {
pool.execute(new Process(serverSocket));
}
} /**
* 运行服务器主线程, 监听客户端请求并返回响应.
*/ /** */
/**
* 启动 HTTP 服务器
*
* @param args
*/
public static void main(String[] args) {
try {
if (args.length != 1) {
System.out.println("这是一个简单的web服务器 ,端口是: 80.");
} else if (args.length == 1) {
PORT = Integer.parseInt(args[0]);
}
} catch (Exception ex) {
System.err.println("服务器初始化错误" + ex.getMessage());
} new SimpleHttpServer();
}
} class Process extends Thread {
private ServerSocket serverSocket;// 服务器Socket Process(ServerSocket serverSocket) {
this.serverSocket = serverSocket;
} public void run() {
try {
Socket client = null;// 客户Socket
client = serverSocket.accept();// 客户机(这里是 IE 等浏览器)已经连接到当前服务器
if (client != null) {
System.out.println("连接到服务器的用户:" + client);
try {
// 第一阶段: 打开输入流
BufferedReader in = new BufferedReader(new InputStreamReader(
client.getInputStream())); System.out.println("客户端发送的请求信息: ***************");
// 读取第一行, 请求地址
System.out.println("http协议头部信息:");
String line = in.readLine();
System.out.println(line);
String resource = line.substring(line.indexOf('/'), line.lastIndexOf('/') - 5);
// 获得请求的资源的地址
resource = URLDecoder.decode(resource, "gbk");// 反编码 String method = new StringTokenizer(line).nextElement().toString();// 获取请求方法,
// GET
// 或者
// POST // 读取浏览器发送过来的请求参数头部信息
while ((line = in.readLine()) != null) {
System.out.println(line); if (line.equals(""))
break;
} System.out.println("http协议头部结束 ***************");
System.out.println("用户请求的资源是:" + resource);
System.out.println("请求的类型是: " + method); String params = null; if (resource.indexOf("?") > -1) {
params = resource.substring(resource.indexOf("?") + 1);
resource = resource.substring(0, resource.indexOf("?"));
} // 显示 POST 表单提交的内容, 这个内容位于请求的主体部分
if ("POST".equalsIgnoreCase(method)) {
if (params != null) {
params += "&" + in.readLine();
} else {
params = in.readLine();
}
} System.out.println("打印提交的数据:");
printParams(params); // 读取资源并返回给客户端
fileReaderAndReturn(resource, client);
// 关闭客户端链接
client.close();
System.out.println("客户端返回完成!");
} catch (Exception e) {
System.out.println("HTTP服务器错误:" + e.getMessage());
}
} } catch (Exception e) {
System.out.println("HTTP服务器错误:" + e.getMessage());
}
} /**
* 读取一个文件的内容并返回给浏览器端.
*
* @param fileName
* 文件名
* @param socket
* 客户端 socket.
* @throws IOException
*/
void fileReaderAndReturn(String fileName, Socket socket) throws IOException {
if ("/".equals(fileName)) {// 设置欢迎页面,呵呵!
fileName = "/index.html";
}
fileName = fileName.substring(1); PrintStream out = new PrintStream(socket.getOutputStream(), true);
File fileToSend = new File(fileName); String fileEx = fileName.substring(fileName.indexOf(".") + 1);
String contentType = null;
// 设置返回的内容类型
// 此处的类型与tomcat/conf/web.xml中配置的mime-mapping类型是一致的。测试之用,就写这么几个。
if ("htmlhtmxml".indexOf(fileEx) > -1) {
contentType = "text/html;charset=GBK";
} else if ("jpegjpggifbpmpng".indexOf(fileEx) > -1) {
contentType = "application/binary";
} if (fileToSend.exists() && !fileToSend.isDirectory()) {
// http 协议返回头
out.println("HTTP/1.0 200 OK");// 返回应答消息,并结束应答
out.println("Content-Type:" + contentType);
out.println("Content-Length:" + fileToSend.length());// 返回内容字节数
out.println();// 根据 HTTP 协议, 空行将结束头信息 FileInputStream fis = null;
try {
fis = new FileInputStream(fileToSend);
} catch (FileNotFoundException e) {
out.println("<h1>404错误!</h1>" + e.getMessage());
}
byte data[];
try {
data = new byte[fis.available()]; fis.read(data);
out.write(data);
} catch (IOException e) {
out.println("<h1>500错误!</h1>" + e.getMessage());
e.printStackTrace();
} finally {
out.close();
try {
fis.close();
} catch (IOException e) { e.printStackTrace();
}
}
} else {
out.println("<h1>404错误!</h1>" + "文件没有找到");
out.close(); } } void printParams(String params) throws IOException {
if (params == null) {
return;
}
String[] maps = params.split("&");
for (String temp : maps) {
String[] map = temp.split("=");
System.out.println(map[0] + "==" + map[1]);
}
} }
简单Web服务器的更多相关文章
- C#中使用Socket实现简单Web服务器
上一篇博客中介绍了怎样使用socket访问web服务器.关键有两个: 熟悉Socket编程: 熟悉HTTP协议. 上一篇主要是通过socket来模拟浏览器向(任何)Web服务器发送(HTTP)请求,重 ...
- tomcat解析之简单web服务器(图)
链接地址:http://gogole.iteye.com/blog/587163 之前有javaeyer推荐了一本书<how tomcat works>,今天晚上看了看,确实不错,第一眼就 ...
- Socket网络编程--简单Web服务器(1)
这一次的Socket系列准备讲Web服务器.就是编写一个简单的Web服务器,具体怎么做呢?我也不是很清楚流程,所以我找来了一个开源的小的Web服务器--tinyhttpd.这个服务器才500多行的代码 ...
- Socket网络编程--简单Web服务器(6)
本来是想实现ssl连接的,但是弄了好久都不成功,就索性不做了,等以后有能力再做了.所以这一小节就是本次的最后一节了.就简单的说几个注意点. 1.加个配置文件 使用单例模式,使用一个类,该类保存一些信息 ...
- Java 18 新特性:简单Web服务器 jwebserver
在今年3月下旬的时候,Java版本已经更新到了18.接下来DD计划持续做一个系列,主要更新从Java 9开始的各种更新内容,但我不全部都介绍,主要挑一些有意思的内容,以文章和视频的方式来给大家介绍和学 ...
- 理解与模拟一个简单web服务器
先简单说下几个概念,根据自己的理解,不正确请见谅. web服务器 首先要知道什么是web服务器,简单说web服务器就是可以使用HTTP传输协议与客户端进行通信的服务器.最初的web服务器只能用来处理静 ...
- 自己实现简单Web服务器,支持GET POST请求
最近项目上遇到一个需求,最后想到的解决方案是自己实现一个web服务器去处理请求,然后再将信息发送到另外一个程序.然后返回处理之后的结果呈现出来. 现在我就来分享一下如何实现的. 通过.NET 为我们提 ...
- java实现简单web服务器(分析+源代码)
在日常的开发中,我们用过很多开源的web服务器,例如tomcat.apache等等.现在我们自己实现一个简单的web服务器,基本的功能就是用户点击要访问的资源,服务器将资源发送到客户端的浏览器.为了简 ...
- Socket网络编程--简单Web服务器(2)
上一小节通过阅读开源的Web服务器--tinyhttpd.大概知道了一次交互的请求信息和应答信息的具体过程.接下来我就自己简单的实现一个Web服务器. 下面这个程序只是实现一个简单的框架出来.这次先实 ...
- Socket网络编程--简单Web服务器(3)
上一小节已经实现了浏览器发送请求,然后服务器给出应答信息,然后浏览器显示出服务器发送过来的网页.一切看起来都是那么的美好.这一小节就准备实现可以根据地址栏url的不同来返回指定的网页.目前还不考虑带参 ...
随机推荐
- Java多线程详解总结
一.基本概念 程序(program): 是为完成特定任务.用某种语言编写的一组指令的集合.即指一 段静态的代码,静态对象. 进程(process):是程序的一次执行过程,或是正在运行的一个程序.是一个 ...
- 【JVM之内存与垃圾回收篇】JVM与Java体系结构
JVM与Java体系结构 前言 作为Java工程师的你曾被伤害过吗?你是否也遇到过这些问题? 运行着的线上系统突然卡死,系统无法访问,甚至直接OOMM! 想解决线上JVM GC问题,但却无从下手. 新 ...
- NVIDIA GPU Turing架构简述
NVIDIA GPU Turing架构简述 本文摘抄自Turing官方白皮书:https://www.nvidia.com/content/dam/en-zz/Solutions/design-vis ...
- JAVA I/O基本操作
JAVA I/O基本操作 JAVA文件操作 JAVA字节流 JAVA字符流 JAVA缓存流 JAVA对象流 JAVA数据流 本文主要借鉴以下博客和网站: how2j.cn 深入理解java中的I/O ...
- nginx 日志功能详解
nginx 日志功能 在 nginx 中有两种日志: access_log:访问日志,通过访问日志可以获取用户的IP.请求处理的时间.浏览器信息等 error_log:错误日志,记录了访问出错的信息, ...
- Spring JPA实现增删改查
1. 创建一个Spring工程 2.配置application文件 spring.datasource.driver-class-name= com.mysql.cj.jdbc.Driver spri ...
- Oracle Dataguard故障转移(failover)操作
注意:故障转移会破坏DG的主从关系,使其变为互不相关的2个数据库,谨慎使用. (一)故障转移操作流程图 (二)故障转移操作流程 备注:以下操作步骤与上面流程图步骤一一对应 STEP1:刷新所有未发送到 ...
- Day02_CMS前端开发
CMS前端开发 1 Vue.js与Webpack研究 参考链接:https://www.cnblogs.com/artwalker/p/13387386.html 2 CMS前端工程创建 2.1 导入 ...
- logging日志基础示例
import logging logger = logging.getLogger() # 获取日志对象 logfile = 'test.log' hdlr = logging.FileHandler ...
- Java 将数据写入全路径下的指定文件
package com.freud.algorithm.other; import java.io.File; import java.io.FileOutputStream; public clas ...