java实现http服务器源码
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
publicclass MyHtmlServer
{
publicstaticvoid main(String[] args) throws IOException { int port=80;
if(args.length>0)
port=Integer.valueOf(args[0]);
new MyHtmlServer().start(port);
}
/**
* 在指定端口启动http服务器
* @param port 指定的端口
* @throws IOException
*/
publicvoid start(int port) throws IOException
{
ServerSocket server = new ServerSocket(port);
System.out.println("server start at "+port+"...........");
while (true) {
Socket client = server.accept();
ServerThread serverthread = new ServerThread(client);
serverthread.start();
}
}
/**
* 服务器响应线程,每收到一次浏览器的请求就会启动一个ServerThread线程
*/
class ServerThread extends Thread {
Socket client;
public ServerThread(Socket client) {
this.client = client;
}
/**
* 读取文件内容,转化为byte数组
* @param filename 文件名
* @return
* @throws IOException
*/
publicbyte[] getFileByte(String filename) throws IOException
{
ByteArrayOutputStream baos=new ByteArrayOutputStream();
File file=new File(filename);
FileInputStream fis=new FileInputStream(file);
byte[] b=newbyte[1000];
int read;
while((read=fis.read(b))!=-1)
{
baos.write(b,0,read);
}
fis.close();
baos.close();
return baos.toByteArray();
}
/**
* 分析http请求中的url,分析用户请求的资源,并将请求url规范化
* 例如请求 "/"要规范成"/index.html","/index"要规范成
"/index.html"
* @param queryurl 用户原始的url
* @return规范化的url,即为用户请求资源的路径
*/
private String getQueryResource(String queryurl)
{
String queryresource=null;
int index=queryurl.indexOf('?');
if(index!=-1)
{
queryresource=queryurl.substring(0,queryurl.indexOf('?'));
}
else
queryresource=queryurl;
index=stIndexOf("/");
if(index+1==queryresource.length())
{
queryresource=queryresource+"index.html";
}
else
{
String filename=queryresource.substring(index+1);
if(!filename.contains("."))
queryresource=queryresource+".html";
}
return queryresource;
}
/**
* 根据用户请求的资源类型,设定http响应头的信息,主要是判断用户请求的文件类型(html、jpg...)
* @param queryresource
* @return
*/
private String getHead(String queryresource)
{
String filename="";
int index=stIndexOf("/");
filename=queryresource.substring(index+1);
String[] filetypes=filename.split("\\.");
String filetype=filetypes[filetypes.length-1];
if(filetype.equals("html"))
{
return"HTTP/1.0200OK\n"+"Content-Type:text/html\n" + "Server:myserver\n" + "\n";
}
elseif(filetype.equals("jpg")||filetype.equals("gif")||file type.equals("png"))
{
return"HTTP/1.0200OK\n"+"Content-Type:image/jpeg\n" + "Server:myserver\n" + "\n";
}
elsereturnnull;
}
@Override
publicvoid run()
{