📄 handler.java
字号:
package webserver;
import java.net.*;
import java.util.regex.*;
import java.io.*;
/**
* 这个类实现了Runable接口,主要处理客户端的请求,并向客户端做出回应
* @author Crise.Lee
* @version 1.0
*/
public class Handler implements Runnable{
Socket socket;
String Rootdoc;
PrintWriter writer;
BufferedOutputStream outputstream;
BufferedReader reader;
File fileroot;
/**
* 服务处理程序的构造函数
* @param socket 接受到来自客户端的请求
* @param _docroot 服务器服务文件夹
* @throws IOException
*/
public Handler(Socket socket,String _docroot) throws IOException
{
System.out.println("in the handler");
this.socket=socket;
try {
fileroot=new File(_docroot).getCanonicalFile();
System.out.println("in handle: _docroot="+_docroot);
/*try { //验证是否可以同时处理多个请求,使线程在创建的开始睡眠20秒
Thread.sleep(20*1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
} catch (IOException e) {
System.out.println("in the handler ioexception");
//e.printStackTrace();
throw new IOException("文件路径:"+_docroot+" 错误");
}
}
public void run()
{
try {
//准备输入输出流
reader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
outputstream=new BufferedOutputStream(socket.getOutputStream());
writer=new PrintWriter(outputstream);
//读入一个HTTP请求字符串
String line=reader.readLine();
//System.out.println("under the line ");
//System.out.println("readline:"+line);
//关闭输入流
socket.shutdownInput();
if(line==null)
{
socket.close();
return;
}
if(line.toUpperCase().startsWith("GET"))
{
String name;
//System.out.println("###### fileroot:"+fileroot);
//提取Get请求的绝对路径
name=isSubstring(line,fileroot);
File file=new File(name).getCanonicalFile();
//检查请求的文件路径是否匹配
if(!file.getAbsolutePath().startsWith(fileroot.getAbsolutePath()))
{
writer.println("HTTP/1.0 403 Forbidden");
writer.println("image/jpeg;charset=GBK");
writer.println("Content-Length:" + file.length());
writer.println("");
writer.flush();
}else if(!file.exists())
{
writer.println("HTTP/1.0 404 File No Found");
writer.println("image/jpeg;charset=GBK");
writer.println("Content-Length:" + file.length());
writer.println("");
writer.flush();
}else if(!file.canRead())
{
writer.println("HTTP/1.0 405 Forbidden");
writer.println("image/jpeg;charset=GBK");
writer.println("Content-Length:" + file.length());
writer.println("");
writer.flush();
}else if(file.isDirectory())
{
writer.println("HTTP/1.0 200 OKay");
//writer.println("image/jpeg;charset=GBK");
//writer.println("Content-Length:" + file.length());
writer.println();
//writer.println("int file.isDirectory()");
//System.err.println("in the isdirectory");
sendDir(outputstream,file.getAbsolutePath(),writer);
writer.flush();
}else
{
writer.println("HTTP/1.0 200 OK");//返回应答消息,并结束应答
if(name.endsWith(".jpg"))
{
writer.println("image/jpeg;charset=GBK");
}
else if(name.endsWith(".html")||name.endsWith(".htm"))
{
writer.println("text/html;charset=GBK");
}
else
{
//do some other
}
writer.println("Content-Length:" + file.length());// 返回内容字节数
writer.println("");
sendFile(outputstream,file.getAbsolutePath(),writer);
writer.flush();
}//if
}else
{
//不是GET命令时候,给出提示,命令没有被执行
writer.println("HTTP/1.0 No Implements");
writer.println();
//System.out.println("not the get order");
}//if
outputstream.flush();
writer.close();
} catch (IOException e) {
//e.printStackTrace();
}
}
/**
* 向客户端发送文件夹的内容
* @param bos
* @param fileName
* @param writer
*/
public void sendDir(BufferedOutputStream bos,String fileName,PrintWriter writer)
{
try{
writer.println("<html><head><title>Directory of ");
writer.println(fileName);
writer.println("</title></head></html><hl>Directory of");
writer.println(fileName);
writer.println("</hl><table border=\"0\">");
File[] contents=new File(fileName).listFiles();
for(int i=0;i<contents.length;i++)
{
writer.write("<tr>");
writer.print("<td><a href=");
//writer.print(fileName);
//writer.print(contents[i].getName());
/*if(contents[i].isDirectory())
writer.print("/");*/
writer.print("\"");
//System.out.println("contents[i]="+contents[i].getAbsolutePath());
writer.print(contents[i].getName());
writer.print("\">");
writer.print(contents[i].getName());
//System.out.println("contents[i].getName="+contents[i].getName());
writer.println("</a></td>");
}
writer.println("</table></body></html>");
writer.flush();
}catch(Exception e)
{
try {
bos.flush();
} catch (IOException e1) {
//e1.printStackTrace();
}
writer.flush();
}
}
/**
* 向客户端发送文件
* @param bos 打印字节流
* @param fileName 文件名
* @param writer 打印字符流
* @throws IOException
*/
public void sendFile(BufferedOutputStream bos,String fileName,PrintWriter writer) throws IOException
{
int read;
bos.flush();
writer.flush();
//System.out.println("in sendfile .....");
try {
BufferedInputStream bis=new BufferedInputStream(new FileInputStream(fileName));
read=bis.read();
while(read!=-1)
{
//System.out.print(read);
bos.write(read);
read=bis.read();
}
// outputstream.flush();
} catch (FileNotFoundException e) {
//e.printStackTrace();
throw new FileNotFoundException("File No Found While Reading");
}finally
{
outputstream.flush();
writer.flush();
}
}
/**
* 转换文件路径
* @param getFileroot
* @param fileroot
* @return
*/
public String isSubstring(String line,File filepath)
{
String name=null,req=null,path=null;
int beginIndex=3,endIndex=0;
Pattern p=Pattern.compile("[ ]{0,}+[/]{1,2}[ ]{0,}+");
endIndex=line.length()-8;
req=line.substring(beginIndex, endIndex);
//System.out.println("**** req="+req);
String strFileroot=filepath.getAbsolutePath();
///将GET文件路径中的'/'转换成windows平台中的‘\’符号
Matcher m=p.matcher(req);
if(m.matches())
{
name=strFileroot;
}else
{
path=req.replaceAll("/",Matcher.quoteReplacement(File.separator));
///System.out.println("path="+path);
int i=0;
//取出路径前面的空和'\'等
while(true)
{
if(path.charAt(i)==' '||path.charAt(i)=='\\')
i++;
else
break;
}
path=path.substring(i);
//抽取出正确的绝对路径
if(path.startsWith(strFileroot))
{
//name=getFileroot.substring(strFileroot.length());
name=path;
}
else
{
name=fileroot+File.separator+path;
}
}
return name;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -