java http server from http://pont.net

原创 2005年05月26日 15:45:00
//***************************************
// HTTP Server 
// fpont June 2000
// server implements HTTP GET method
//***************************************


import java.net.*;
import java.io.*;
import java.util.*;
import java.lang.*;


public class httpServer 
{
    
    public static void main(String args[]) {
	
	int port;
	ServerSocket server_socket;
	
	
	try { 
	    port = Integer.parseInt(args[0]);
	}
	catch (Exception e) {
	    port = 1500;
	}
	

	try {
	    
	    server_socket = new ServerSocket(port);
	    System.out.println("httpServer running on port " + 
			       server_socket.getLocalPort());
	    
	    // server infinite loop
	    while(true) {
		Socket socket = server_socket.accept();
		System.out.println("New connection accepted " +
				   socket.getInetAddress() +
				   ":" + socket.getPort());
		
		// Construct handler to process the HTTP request message.
		try {
		    httpRequestHandler request = 
			new httpRequestHandler(socket);
		    // Create a new thread to process the request.
		    Thread thread = new Thread(request);
		    
		    // Start the thread.
		    thread.start();
		}
		catch(Exception e) {
		    System.out.println(e);
		}
	    }
	}
	
	catch (IOException e) {
	    System.out.println(e);
	}
    }
}


 
class httpRequestHandler implements Runnable
{
    final static String CRLF = "/r/n";
    Socket socket;
    InputStream input;
    OutputStream output;
    BufferedReader br;

    // Constructor
    public httpRequestHandler(Socket socket) throws Exception 
    {
	this.socket = socket;
	this.input = socket.getInputStream();
	this.output = socket.getOutputStream();
	this.br = 
	    new BufferedReader(new InputStreamReader(socket.getInputStream()));
    }
    
    // Implement the run() method of the Runnable interface.
    public void run()
    {
	try {
	    processRequest();
	}
	catch(Exception e) {
	    System.out.println(e);
	}
    }
    
    private void processRequest() throws Exception
    {
	while(true) {
	    
	    String headerLine = br.readLine();
	    System.out.println(headerLine);
	    if(headerLine.equals(CRLF) || headerLine.equals("")) break;
	    
	    StringTokenizer s = new StringTokenizer(headerLine);
	    String temp = s.nextToken();
	    
	    if(temp.equals("GET")) {

		String fileName = s.nextToken();
		fileName = "." + fileName ;
		
		// Open the requested file.
		FileInputStream fis = null ;
		boolean fileExists = true ;
		try 
		    {
			fis = new FileInputStream( fileName ) ;
		    } 
		catch ( FileNotFoundException e ) 
		    {
			fileExists = false ;
		    }
		
		// Construct the response message.
		String serverLine = "Server: fpont simple java httpServer";
		String statusLine = null;
		String contentTypeLine = null;
		String entityBody = null;
		String contentLengthLine = "error";
		if ( fileExists )
		    {
			statusLine = "HTTP/1.0 200 OK" + CRLF ;
			contentTypeLine = "Content-type: " + 
			    contentType( fileName ) + CRLF ;
			contentLengthLine = "Content-Length: " 
			    + (new Integer(fis.available())).toString() 
			    + CRLF;
		    }
		else
		    {
			statusLine = "HTTP/1.0 404 Not Found" + CRLF ;
			contentTypeLine = "text/html" ;
			entityBody = "<HTML>" + 
			    "<HEAD><TITLE>404 Not Found</TITLE></HEAD>" +
			    "<BODY>404 Not Found" 
			    +"<br>usage:http://yourHostName:port/"
			    +"fileName.html</BODY></HTML>" ;
		    }
		
		// Send the status line.
		output.write(statusLine.getBytes());
		
		// Send the server line.
		output.write(serverLine.getBytes());
		
		// Send the content type line.
		output.write(contentTypeLine.getBytes());
		
		// Send the Content-Length
		output.write(contentLengthLine.getBytes());
		
		// Send a blank line to indicate the end of the header lines.
		output.write(CRLF.getBytes());
		
		// Send the entity body.
		if (fileExists)
		    {
			sendBytes(fis, output) ;
			fis.close();
		    }
		else
		    {
			output.write(entityBody.getBytes());
		    }
				
	    }
	}
	
	try {
	    output.close();
	    br.close();
	    socket.close();
	}
	catch(Exception e) {}
    }
    
    private static void sendBytes(FileInputStream fis, OutputStream os) 
	throws Exception
    {
	// Construct a 1K buffer to hold bytes on their way to the socket.
	byte[] buffer = new byte[1024] ;
	int bytes = 0 ;
	
	// Copy requested file into the socket's output stream.
	while ((bytes = fis.read(buffer)) != -1 ) 
	    {
		os.write(buffer, 0, bytes);
	    }
    }
    
    private static String contentType(String fileName)
    {
	if (fileName.endsWith(".htm") || fileName.endsWith(".html"))
	    {
		return "text/html";
	    }
	
	return "";
	
    }
    
}






相关文章推荐

{转载}Linux Top 命令解析 比较详细 {from:http://www.jb51.net/LINUXjishu/34604.html}

TOP是一个动态显示过程,即可以通过用户按键来不断刷新当前状态.如果在前台执行该命令,它将独占前台,直到用户终止该程序为止.比较准确的说,top命令提供了实时的对系统处理器的状态监视.它将显示系统中C...

面试常见问题的经典回答 from http://www.nowamagic.net/

转自 http://www.nowamagic.net/librarys/veda/detail/1234 请你自我介绍一下你自己 回答提示:一般人回答这个问题过于平常,只说姓名、年龄、爱好、...

FAT文件系统原理from: http://www.sjhf.net

FAT文件系统原理                          ——http://www.sjhf.net 文本结构索引:   图片表格索引: 表1...
  • lineter
  • lineter
  • 2011年11月11日 09:49
  • 887

Embedded .NET HTTP Server

翻译至:http://www.codeproject.com/Articles/25050/Embedded-NET-HTTP-Server 介绍 现在HTTP已经无处不在。如果你想了解某些东西,...

ASP.net--Response对象、Server对象、无状态Http、Cookie

Response对象 •响应的缓存输出! •Response.write(“hello world!”); •Response对象成员: •Buffer: •BufferOutPut ...

【.Net MF网络开发板研究-02】Http Server功能演示

在上一篇博文中介绍的Web Server,其实是Socket编程应用,我们这篇文章介绍的是真正的Http Server,支持GET和POST功能。 同样我们还是在官方示例Http Server上进行修...

Java调用.Net写的WebService报异常:服务器未能识别 HTTP 头 SOAPAction 的值

异常及解决方案 使用JAX-WS调用.Net写的WebService报了如下异常: javax.xml.ws.soap.SOAPFaultException: System.Web.Ser...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:java http server from http://pont.net
举报原因:
原因补充:

(最多只允许输入30个字)