一个简单的Web服务器

/*
 * 文件名:WebServer.java
 * 环境: GNU/Linux Ubuntu 7.04 + Eclipse 3.2
 * 功能:一个简单的Web服务器
 * 作者:88250
 * 日期:2007.4.22
 * E-mail & MDN: [email protected]
 * QQ:845765
 
*/

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

public   class  WebServer
{
    
public   static   void  main(String argv[])  throws  Exception
    {
    String requestMessageLine;
    String fileName;
    ServerSocket listenSocket 
=   new  ServerSocket( 6789 );
    Socket connectionSocket 
=  listenSocket.accept();
    BufferedReader inFromClient 
=   new  BufferedReader( new  InputStreamReader(
        connectionSocket.getInputStream()));
    DataOutputStream outToClient 
=   new  DataOutputStream(connectionSocket
        .getOutputStream());
    requestMessageLine 
=  inFromClient.readLine();
    System.out.println(requestMessageLine);
    StringTokenizer tokenizedLine 
=   new  StringTokenizer(requestMessageLine);
    
if  (tokenizedLine.nextToken().equals( " GET " ))
    {
        fileName 
=  tokenizedLine.nextToken();
        
if  (fileName.startsWith( " / " ==   true )
        fileName 
=  fileName.substring( 1 );
        File file 
=   new  File(fileName);
        
int  numOfBytes  =  ( int ) file.length();
        FileInputStream inFile 
=   new  FileInputStream(fileName);
        
byte [] fileInBytes  =   new   byte [numOfBytes];
        inFile.read(fileInBytes);
        outToClient.writeBytes(
" HTTP/1.0 200 Document Follow " );
        
if  (fileName.endsWith( " .jpg " ))
        outToClient.writeBytes(
" Content-Type:image/jpeg " );
        
if  (fileName.endsWith( " .gif " ))
        outToClient.writeBytes(
" Content-Type:image/gif " );
        
if  (fileName.endsWith( " .txt " ))
        outToClient.writeBytes(
" Content-Type:txt " );
        outToClient.writeBytes(
" Content-Length: "   +  numOfBytes  +   " " );
        outToClient.writeBytes(
" " );
        outToClient.write(fileInBytes, 
0 , numOfBytes);
        connectionSocket.close();
    }
    
else
        System.out.println(
" Bad Request Message " );
    }
}
 
测试结果如下:
一个简单的Web服务器_第1张图片

你可能感兴趣的:(一个简单的Web服务器)