用Java实现简单的web服务器

运行结果:

用Java实现简单的web服务器用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();
}
}
上一篇:Python Numpy Array


下一篇:正则表达式awk