自己如何实现简单的http服务器
2008-04-25 16:15
726 查看
文件名:MyhttpServerTest.java
import java.io.* ;
import java.net.* ;
import java.util.* ;
/**
* main
*/
public class MyhttpServerTest{
String m_szServerName;//server name
String m_szVersion;//server version
int m_nServerPort;//port
public MyhttpServerTest(String szServerName,String szVersion,int nServerPort){
this.m_szServerName =szServerName;
this.m_szVersion =szVersion;
this.m_nServerPort=nServerPort;
}
/**
* show version information
*/
public void showServerInformation(){
System.out.println("欢迎使用Newman的http服务器!");
System.out.println("Server Name : "+this.m_szServerName);
System.out.println("Server Version: "+this.m_szVersion );
}
public void start (){
this.showServerInformation();
try{
ServerSocket server=new ServerSocket(this.m_nServerPort );
while(true){
Socket client=server.accept();
(new httpClientThread(client)).run();
}
}
catch(Exception e){
e.printStackTrace();
System.exit(1);
}
}
public static void main(String args[]){
MyhttpServerTest server=new MyhttpServerTest("MyhttpServerTest","1.0",80);
server.start();
}
}
class httpClientThread implements Runnable {
Socket m_sClient;
httpRequest m_Request;
httpClientThread(Socket sClient)throws IOException{
this.m_sClient =sClient;
this.m_Request =new httpRequest(this.m_sClient );
}
public void run(){
try{
System.out.println(this.getConnectInfo());
BufferedOutputStream out=new BufferedOutputStream(this.m_sClient .getOutputStream ());
System.out.println( this.m_Request.getLog());
if(this.m_Request.isGetRequest())
this.processGetRequest(this.m_Request,out);
System.out.println("Request completed. Closing connection.");
this.m_sClient .close ();
}
catch(IOException e){
System.out.println("IOException occurred .");
e.printStackTrace();
}
}
/**
* get Connect Info
*/
public String getConnectInfo(){
String szClientHostName=this.m_sClient .getInetAddress().getHostName ();
String szClientAddress=this.m_sClient .getInetAddress ().getHostAddress();
int ClientPort=this.m_sClient .getPort ();
String szRet="";
szRet="Accepted connection from "+szClientHostName+"("+szClientAddress+") "+"on port "+ClientPort+".";
return szRet;
}
void processGetRequest(httpRequest request,BufferedOutputStream out)throws IOException {
String szFileName=request.getFileName ();
File file=new File (szFileName);
if(file.exists ())
this.sendFile (out,file);
else{//文件不存在时
System.out.println ("File "+file.getCanonicalPath()+" does not exist.");
String notfound="<html><head><title>Not Found</title></head><body><h1>"+
"Error 404-file not found</h1><p>"+
"File Name: "+file+" not found"+"<br>"+
"<a href=index.htm>Return Index</a>"+
"</body></html>";
file://out.write(new String("http/1.0 404 no found").getBytes ());
out.write (new String ("http/1.0 200 OK").getBytes ());
out.write(new String("Content_Length:"+notfound.length()+2).getBytes());
out.write(new String("Content_Type:text/html").getBytes ());
out.write(new String(" ").getBytes());
out.write(notfound.getBytes ());
out.flush();
}
}
void sendFile(BufferedOutputStream out,File file){
try{
DataInputStream din=new DataInputStream (new FileInputStream (file ));
int len=(int)file.length();
byte buffer[]=new byte [len];
din.readFully (buffer);
din.close();
out.write (new String ("http/1.0 200 OK").getBytes ());
out.write (new String ("Content-Length: "+buffer.length +"").getBytes ());
out.write (new String ("Content-Type: text/html").getBytes ());
out.write (buffer);
out.flush ();
out.close ();
System.out.println("File sent: "+file.getCanonicalPath());
System.out.println("Number of bytes: "+len);
}
catch(Exception e){
try{
out.write(("http/1.0 400 " + "No can do" + "").getBytes());
out.write("Content-Type: text/html".getBytes());
}
catch(IOException ioe){
System.out.println("Error retrieving "+file);
}
}
}
}
Vector m_vLines=new Vector ();
Socket m_sClient;
httpInputStream m_In;
httpRequest(Socket client)throws IOException{
this.m_sClient =client;
this.m_In =new httpInputStream(this.m_sClient.getInputStream());
this.getRequest ();
}
public String getLog(){
StringBuffer szRet=new StringBuffer() ;
szRet.append ("Received the following request:"+"");
Enumeration enum=m_vLines.elements ();
String szstr1="";
while(enum.hasMoreElements()){
szstr1=(String)enum.nextElement();
szRet.append (szstr1+"");
}
return szstr1.toString();
}
boolean isGetRequest() {
if(this.m_vLines .size ()>0){
String firstline=(String)this.m_vLines.elementAt (0);
if(firstline.length ()>0)
if(firstline.substring(0,3).equalsIgnoreCase ("GET"))
return true;
}
return false;
}
String getFileName() {
if(this.m_vLines .size ()>0){
String firstline=(String)this.m_vLines.elementAt (0);
String filename=firstline.substring (firstline.indexOf (" ")+1);
int n=filename.indexOf (" ");
if(n!=-1)
filename=filename.substring (0,n);
try{
if(filename.charAt(0)=='/' )
filename=filename.substring (1);
}
catch(StringIndexOutOfBoundsException ex){
}
if(filename.equals (""))
filename="index.htm";
if(filename.charAt (filename.length ()-1)=='/')
filename+="index.htm";//not understand
return filename;
}
else
return "";
}
public httpInputStream getInputStream(){
return this.m_In ;
}
public httpRequest getRequest() throws IOException {
String line;
while(true){
line=this.m_In.readLine ();
if(line.length ()>0)
this.m_In.addLine(line);
else
break;
}
return this;
}
/**
* only use to recognize methed "get"
*/
class httpInputStream extends FilterInputStream {
httpInputStream(InputStream in){
super(in);
}
public void addLine(String line) {
m_vLines .addElement(line);
}
public String readLine() throws IOException {
StringBuffer result=new StringBuffer ();
boolean finished=false;
boolean isenter=false;
while(!finished){
int ch=-1;
ch=read();
if((isenter)&&(ch==10)){// if it is ""
result.setLength(result.length()-1);//had added "",remove it
return result.toString ();
}
if(ch==13)//if enter pressed
isenter=true;
else
isenter=false;
if(ch==-1)//end
return result.toString ();
else
result.append ((char)ch);
}
return result.toString ();
}
}
}
请多指教
import java.io.* ;
import java.net.* ;
import java.util.* ;
/**
* main
*/
public class MyhttpServerTest{
String m_szServerName;//server name
String m_szVersion;//server version
int m_nServerPort;//port
public MyhttpServerTest(String szServerName,String szVersion,int nServerPort){
this.m_szServerName =szServerName;
this.m_szVersion =szVersion;
this.m_nServerPort=nServerPort;
}
/**
* show version information
*/
public void showServerInformation(){
System.out.println("欢迎使用Newman的http服务器!");
System.out.println("Server Name : "+this.m_szServerName);
System.out.println("Server Version: "+this.m_szVersion );
}
public void start (){
this.showServerInformation();
try{
ServerSocket server=new ServerSocket(this.m_nServerPort );
while(true){
Socket client=server.accept();
(new httpClientThread(client)).run();
}
}
catch(Exception e){
e.printStackTrace();
System.exit(1);
}
}
public static void main(String args[]){
MyhttpServerTest server=new MyhttpServerTest("MyhttpServerTest","1.0",80);
server.start();
}
}
class httpClientThread implements Runnable {
Socket m_sClient;
httpRequest m_Request;
httpClientThread(Socket sClient)throws IOException{
this.m_sClient =sClient;
this.m_Request =new httpRequest(this.m_sClient );
}
public void run(){
try{
System.out.println(this.getConnectInfo());
BufferedOutputStream out=new BufferedOutputStream(this.m_sClient .getOutputStream ());
System.out.println( this.m_Request.getLog());
if(this.m_Request.isGetRequest())
this.processGetRequest(this.m_Request,out);
System.out.println("Request completed. Closing connection.");
this.m_sClient .close ();
}
catch(IOException e){
System.out.println("IOException occurred .");
e.printStackTrace();
}
}
/**
* get Connect Info
*/
public String getConnectInfo(){
String szClientHostName=this.m_sClient .getInetAddress().getHostName ();
String szClientAddress=this.m_sClient .getInetAddress ().getHostAddress();
int ClientPort=this.m_sClient .getPort ();
String szRet="";
szRet="Accepted connection from "+szClientHostName+"("+szClientAddress+") "+"on port "+ClientPort+".";
return szRet;
}
void processGetRequest(httpRequest request,BufferedOutputStream out)throws IOException {
String szFileName=request.getFileName ();
File file=new File (szFileName);
if(file.exists ())
this.sendFile (out,file);
else{//文件不存在时
System.out.println ("File "+file.getCanonicalPath()+" does not exist.");
String notfound="<html><head><title>Not Found</title></head><body><h1>"+
"Error 404-file not found</h1><p>"+
"File Name: "+file+" not found"+"<br>"+
"<a href=index.htm>Return Index</a>"+
"</body></html>";
file://out.write(new String("http/1.0 404 no found").getBytes ());
out.write (new String ("http/1.0 200 OK").getBytes ());
out.write(new String("Content_Length:"+notfound.length()+2).getBytes());
out.write(new String("Content_Type:text/html").getBytes ());
out.write(new String(" ").getBytes());
out.write(notfound.getBytes ());
out.flush();
}
}
void sendFile(BufferedOutputStream out,File file){
try{
DataInputStream din=new DataInputStream (new FileInputStream (file ));
int len=(int)file.length();
byte buffer[]=new byte [len];
din.readFully (buffer);
din.close();
out.write (new String ("http/1.0 200 OK").getBytes ());
out.write (new String ("Content-Length: "+buffer.length +"").getBytes ());
out.write (new String ("Content-Type: text/html").getBytes ());
out.write (buffer);
out.flush ();
out.close ();
System.out.println("File sent: "+file.getCanonicalPath());
System.out.println("Number of bytes: "+len);
}
catch(Exception e){
try{
out.write(("http/1.0 400 " + "No can do" + "").getBytes());
out.write("Content-Type: text/html".getBytes());
}
catch(IOException ioe){
System.out.println("Error retrieving "+file);
}
}
}
}
Vector m_vLines=new Vector ();
Socket m_sClient;
httpInputStream m_In;
httpRequest(Socket client)throws IOException{
this.m_sClient =client;
this.m_In =new httpInputStream(this.m_sClient.getInputStream());
this.getRequest ();
}
public String getLog(){
StringBuffer szRet=new StringBuffer() ;
szRet.append ("Received the following request:"+"");
Enumeration enum=m_vLines.elements ();
String szstr1="";
while(enum.hasMoreElements()){
szstr1=(String)enum.nextElement();
szRet.append (szstr1+"");
}
return szstr1.toString();
}
boolean isGetRequest() {
if(this.m_vLines .size ()>0){
String firstline=(String)this.m_vLines.elementAt (0);
if(firstline.length ()>0)
if(firstline.substring(0,3).equalsIgnoreCase ("GET"))
return true;
}
return false;
}
String getFileName() {
if(this.m_vLines .size ()>0){
String firstline=(String)this.m_vLines.elementAt (0);
String filename=firstline.substring (firstline.indexOf (" ")+1);
int n=filename.indexOf (" ");
if(n!=-1)
filename=filename.substring (0,n);
try{
if(filename.charAt(0)=='/' )
filename=filename.substring (1);
}
catch(StringIndexOutOfBoundsException ex){
}
if(filename.equals (""))
filename="index.htm";
if(filename.charAt (filename.length ()-1)=='/')
filename+="index.htm";//not understand
return filename;
}
else
return "";
}
public httpInputStream getInputStream(){
return this.m_In ;
}
public httpRequest getRequest() throws IOException {
String line;
while(true){
line=this.m_In.readLine ();
if(line.length ()>0)
this.m_In.addLine(line);
else
break;
}
return this;
}
/**
* only use to recognize methed "get"
*/
class httpInputStream extends FilterInputStream {
httpInputStream(InputStream in){
super(in);
}
public void addLine(String line) {
m_vLines .addElement(line);
}
public String readLine() throws IOException {
StringBuffer result=new StringBuffer ();
boolean finished=false;
boolean isenter=false;
while(!finished){
int ch=-1;
ch=read();
if((isenter)&&(ch==10)){// if it is ""
result.setLength(result.length()-1);//had added "",remove it
return result.toString ();
}
if(ch==13)//if enter pressed
isenter=true;
else
isenter=false;
if(ch==-1)//end
return result.toString ();
else
result.append ((char)ch);
}
return result.toString ();
}
}
}
请多指教
相关文章推荐
- 自己如何实现简单的http服务器
- 基于tcp自己实现简单的HTTP服务器
- mfc学习笔记之如何自己动手实现最简单的mfc程序
- 如何自己实现模板类(简单案例——顺序表)
- 【NROS-00】自己实现一个简单操作系统
- 如何在ns2中实现一个简单的网络协议
- 如何实现一个简单的工作流审批引擎——请看
- 一个简单抽奖算法的实现以及如何预防超中
- 一个简单地list侧滑菜单,自己实现不是梦
- 如何写一个简单的webserver(一):最简实现
- 自己实现HTTP服务器
- C#实现一个最简单的HTTP服务器
- 如何在C语言中实现简单的泛型编程(一)
- 如何在C语言中实现简单的泛型编程(二)
- 如何在自己网页上实现加入google groups功能
- 《小白兔到大黑牛》第二篇基于源码自己实现简单的ArrayList中简单方法
- Linux下利用线程池模型+epoll实现简单的HTTP服务器
- Python实现简单的HTTP服务器
- PHP实现基于Swoole简单的HTTP服务器
- 传智:自己简单实现一个struts2框架的demo