用Java实现简单的web服务器
运行结果:


1、WebServer.java文件
package webserver; import java.io.*;
import java.net.*; public class WebServer { /**
* web服务器:实现200和404操作
* 原理:
* 服务器监听一个端口,并读取浏览器的请求信息,从该信息提取出访问的资源(这里为文件名)。并在工作目录下查找是否有该资源,有则输出资源内容,否则返回404
* 测试方法:
* 1、用String path=System.getProperty("user.dir");获取当前的工作目录,并在该目录下放要测试的文件
* 2、访问127.0.0.1:8080/test.html
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ServerSocket server = null;
Socket s=null;
try
{
server=new ServerSocket(8080,3,InetAddress.getByName("127.0.0.1"));
}catch(Exception e)
{
e.printStackTrace();
}
while(true)
{
try{
s=server.accept();
OutputStream output=s.getOutputStream();
InputStream input=s.getInputStream(); //接收请求信息
Request request=new Request(input);
String filename=request.getUri();
//System.out.println(filename); //处理并响应请求信息
Response response=new Response(output,filename);
response.response(); }catch(Exception e)
{
e.printStackTrace();
}
}
} }
2、Request.java
package webserver;
import java.io.*;
public class Request {
/*
* 接收请求的信息,并返回资源(文件名)
* */
InputStream input;
public Request(InputStream input)
{
this.input=input;
}
public String getUri() throws IOException
{
String content=null,str=null;
StringBuffer request = new StringBuffer();
byte[] buffer = new byte[2048];
int i = 0; try {
i = input.read(buffer); //读取内容并存入buffer数组中,并返回读取的的字节数。
} catch (IOException e) {
e.printStackTrace();
i = -1;
}
//将buffer数组转换为字符串
for(int k = 0; k < i; k++) {
request.append((char)buffer[k]);
}
content=request.toString();
/*
*以下方法错误!用该返回会使浏览器不断处于请求连接状态
* BufferedReader br=new BufferedReader(new InputStreamReader(input));
while((str=br.readLine())!=null)
{
content=content+str+"\r\n";
}
*/
if(content!=null)
return getFilename(content);
else return null;
}
/*提取文件名*/
public String getFilename(String content)
{
int a,b;
a=content.indexOf(' ');
if(a!=-1)
{
b=content.indexOf('?',a+1);
if(b==-1)b=content.indexOf(' ',a+1);
return content.substring(a+2,b);
}
return null;
}
}
3、Response.java
package webserver; import java.io.*;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream; public class Response {
/**
* 响应并处理请求信息
*/
public OutputStream output;
public String filename;
private static final int BUFFER_SIZE = 1024;
public Response(OutputStream output,String filename)
{
this.output=output;
this.filename=filename;
}
public void response() throws IOException
{
String path=System.getProperty("user.dir");//获取当前的工作目录
byte[] buffer = new byte[BUFFER_SIZE];
int ch;
FileInputStream fis = null;
//System.out.println(path+File.separator+filename);
if(path!=null&&filename!=null)
{
File file=new File(path,filename);
String str="";
/*必须添加响应头,否则无法以html格式显示内容*/
if(file.exists())
{
fis = new FileInputStream(file);
str = "HTTP/1.1 200 OK \r\n" +
"Content-Type: text/html\r\n" +
"\r\n" ;
output.write(str.getBytes());
ch = fis.read(buffer);
while(ch != -1) {
output.write(buffer, 0, ch);
ch = fis.read(buffer, 0, BUFFER_SIZE);
}
}
else
{
str = "HTTP/1.1 404 File Not Found \r\n" +
"Content-Type: text/html\r\n" +
"Content-Length: 100\r\n" +
"\r\n" +
"<h1>404 File Not Found!</h1>";
output.write(str.getBytes());
}
}
output.close();
}
}
用Java实现简单的web服务器的更多相关文章
- java实现一个简单的Web服务器
注:本段内容来源于<JAVA 实现 简单的 HTTP服务器> 1. HTTP所有状态码 状态码 状态码英文名称 中文描述 100 Continue 继续.客户端应继续其请求 101 Swi ...
- 深入剖析tomcat之一个简单的web服务器
这个简单的web服务器包含三个类 HttpServer Request Response 在应用程序的入口点,也就是静态main函数中,创建一个HttpServer实例,然后调用其await()方法. ...
- Tomcat剖析(一):一个简单的Web服务器
Tomcat剖析(一):一个简单的Web服务器 1. Tomcat剖析(一):一个简单的Web服务器 2. Tomcat剖析(二):一个简单的Servlet服务器 3. Tomcat剖析(三):连接器 ...
- 徒手用Java来写个Web服务器和框架吧<第三章:Service的实现和注册>
徒手用Java来写个Web服务器和框架吧<第一章:NIO篇> 徒手用Java来写个Web服务器和框架吧<第二章:Request和Response> 这一章先把Web框架的功能说 ...
- 徒手用Java来写个Web服务器和框架吧<第二章:Request和Response>
徒手用Java来写个Web服务器和框架吧<第一章:NIO篇> 接上一篇,说到接受了请求,接下来就是解析请求构建Request对象,以及创建Response对象返回. 多有纰漏还请指出.省略 ...
- Tomcat学习笔记(一)一个简单的Web服务器
内容为<深入剖析Tomcat>第一章重点,以及自己的总结,如有描述不清的,可查看原书. 一.HTTP协议: 1.定义:用于服务器与客户端的通讯的协议,允许web服务器和浏览器通过互联网进行 ...
- 自己模拟的一个简单的web服务器
首先我为大家推荐一本书:How Tomcat Works.这本书讲的很详细的,虽然实际开发中我们并不会自己去写一个tomcat,但是对于了解Tomcat是如何工作的还是很有必要的. Servlet容器 ...
- 各种容器与服务器的区别与联系 Servlet容器 WEB容器 Java EE容器 应用服务器 WEB服务器 Java EE服务器
转自:https://blog.csdn.net/tjiyu/article/details/53148174 各种容器与服务器的区别与联系 Servlet容器 WEB容器 Java EE容器 应用服 ...
- 《深度解析Tomcat》 第一章 一个简单的Web服务器
本章介绍Java Web服务器是如何运行的.从中可以知道Tomcat是如何工作的. 基于Java的Web服务器会使用java.net.Socket类和java.net.ServerSocket类这两个 ...
随机推荐
- Js中文排序(拼音首字母)
演示地址:http://lar5.sinaapp.com/ 1.index.html <html xmlns="http://www.w3.org/1999/xhtml"&g ...
- Virtual Box下配置Host-Only联网方式详解
其实网络这类相关的文章很多,我只是想结合自己的实际情况,把我的经验写下来,给那些需要的人们吧. 主机:windows 7 虚拟机:CentOS6.0 VirtualBox:4.2.0 虚拟机在安装好之 ...
- iOS开发——高级篇——iOS中常见的设计模式(MVC/单例/委托/观察者)
关于设计模式这个问题,在网上也找过一些资料,下面是我自己总结的,分享给大家 如果你刚接触设计模式,我们有好消息告诉你!首先,多亏了Cocoa的构建方式,你已经使用了许多的设计模式以及被鼓励的最佳实践. ...
- 学习JVM GarbageCollection
前言 Java和C++之间显著的一个区别就是对内存的管理.Java和C++把内存管理的权利赋予给开发人员的方式不同,Java拥有一套自动的内存回收系统(Garbage Collection,GC)简称 ...
- [Linux]Linux系统调用列表
本文列出了大部分常见的Linux系统调用,并附有简要中文说明. 以下是Linux系统调用的一个列表,包含了大部分常用系统调用和由系统调用派生出的的函数.这可能是你在互联网上所能看到的唯一一篇中文注释的 ...
- .NET LINQ 元素操作
元素操作 元素操作从一个序列返回单个特定元素. 方法 方法名 说明 C# 查询表达式语法 Visual Basic 查询表达式语法 更多信息 ElementAt 返回集合中指定索引处的元素. ...
- Jmeter连接Mysql
1.下载连接mysql数据库jar包,地址:http://files.cnblogs.com/files/xiaoxitest/mysql-connector-java-5.1.28.zip(因不支持 ...
- InnoDB VS MyISAM
首先都是MySql存储引擎.数据库的考虑点一般就是事务(ACID),然后牵扯出的锁机制.如果你需要事务,那就只能选InnoDB了.如果你还需要外键约束,你也只能选择InnoDB.这个是两者最大的区别. ...
- WCF创建RESTService
这篇博客将介绍在WCF中创建REST服务相关内容.首先先看一下的项目结构: Contract,Service两个工程为类库工程,需要添加System.ServiceModel, System.Serv ...
- PIL中分离通道发生“AttributeError: 'NoneType' object has no attribute 'bands'”
解决方法: 这个貌似是属于一个bug 把Image.py中的1500行左右的split函数改成如下即可: def split(self): "Split image into bands&q ...