<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    沙漠中的魚

    欲上天堂,先下地獄
    posts - 0, comments - 56, trackbacks - 0, articles - 119
      BlogJava :: 首頁 ::  :: 聯系 :: 聚合  :: 管理

    最簡單的web服務器代碼(Java)

    Posted on 2009-06-19 16:36 沙漠中的魚 閱讀(1452) 評論(0)  編輯  收藏 所屬分類: 系統架構JavaJava基礎

    HttpServer.java

    package htmlbrowser;

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.util.Properties;
    import java.io.IOException;
    import java.util.Enumeration;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.io.PrintStream;


    public class HttpServer
    {
        
    private int iPort = 8080//default port
        public static String Basic_Root=System.getProperty("user.dir");
        
    public static String WEB_ROOT = System.getProperty("user.dir"+
                                        File.separator 
    + "webroot";
        
    public static int count=0;

        
    public HttpServer()
        
    {
            System.out.println(
    "歡迎使用Erik‘s 快速Web服務器,本服務器只支持靜態網頁。");
            System.out.println(
    "檢查配置文件及網頁文件夾");
            getConfig();
            start();
        }


        
    public static void main(String[] args)
        
    {
            HttpServer httpserver 
    = new HttpServer();
        }


        
    private void getConfig()
        
    {
            File fileCon
    =new File(Basic_Root,"config.ini");
            File fileDir
    =new File(WEB_ROOT);
            File fileWeb
    =new File(WEB_ROOT,"index.htm");
            
    if(!fileCon.exists())
            
    {
                System.out.println(
    "配置文件Config.ini損壞,重建中");
                reBuildConfig(fileCon);
            }

            
    if (!fileDir.exists())
            
    {
                System.out.println(
    "網頁存放文件夾不存在,重建中");
                fileDir.mkdir();
                System.out.print(
    "完成!請在");
                System.out.println(WEB_ROOT
    +"中放置網頁文件");
                System.out.println(
    "Web服務器將重新初始化");
                getConfig();
            }

            
    if (!fileWeb.exists())
            
    {
                reBuildWeb(fileWeb);
            }

            Properties pps 
    = new Properties();

            
    try
            
    {
                pps.load(
    new FileInputStream("config.ini"));
                Enumeration enumer 
    = pps.propertyNames();
                String strKey 
    = (String) enumer.nextElement();
                String strValue 
    = pps.getProperty(strKey);
                
    if (strValue.equals(""!= true)
                
    {
                    WEB_ROOT 
    = strValue;
                }

                System.out.println(
    "網頁文件的存放路徑為: "+WEB_ROOT);
                strKey 
    = (String) enumer.nextElement();
                strValue 
    = pps.getProperty(strKey);
                
    if (strValue.equals(""!= true)
                
    {
                    iPort 
    = Integer.parseInt(strValue);
                }

                System.out.println(
    "Web服務器訪問端口為:"+iPort);
                System.out.println(
    "您可以修改Config.ini文件重新設定以上配置");
                System.out.println(
    "啟動檢查完成,服務器初始化中");

            }

            
    catch (IOException ex)
            
    {
                ex.printStackTrace();
            }


        }


        
    public void start()
        
    {

            System.out.println(
    "Web 服務器啟動中");
            ServerSocket serverSocket;
            
    try
            
    {
                serverSocket 
    = new ServerSocket(iPort);
                System.out.println(
    "Web 啟動完成!");
                System.out.println(
    "您現在可以在瀏覽器中訪問http://localhost:8080/,以測試服務器是否運行");
                
    while (true)
                
    {
                    Socket socket 
    = null;
                    InputStream input 
    = null;
                    OutputStream output 
    = null;
                    System.out.println(
    "等待連接");
                    socket 
    = serverSocket.accept();
                    System.out.println(socket.getInetAddress().toString()
    +"請求連接");
                    input
    =socket.getInputStream();
                    output
    =socket.getOutputStream();
                    System.out.println(
    "服務器開始處理第"+(++count)+"次連接");
                    
    //開始處理并分析請求信息
                    Request request=new Request(input);
                    request.parse();

                    
    //開始發送請求資源
                    Response response=new Response(output);
                    response.setRequest(request);
                    response.sendStaticResource();

                    
    //關系連接
                    socket.close();
                    System.out.println(
    "連接已關閉!");

                }

            }

            
    catch(Exception ex)
            
    {
                ex.printStackTrace();
                System.out.println(
    "3");
                
    //continue;
            }

        }

        
    private void reBuildConfig(File file)
        
    {

            
    try
            
    {
                file.createNewFile();
                FileOutputStream fos
    =new FileOutputStream(file);
                PrintStream sp
    =new PrintStream(fos);
                sp.println(
    "WEB_ROOT=");
                sp.println(
    "PORT=");
                sp.close();
                System.out.println(
    "配置文件Config.ini創建成功,您可以修改WEB_ROOT的值改變網頁文件的存放路徑,修改PORT的值改變訪問端口!");
            }

            
    catch (IOException ex)
            
    {
                ex.printStackTrace();
                System.out.println(
    "重建配置文件Config.ini失敗");
                System.out.println(
    "服務器將使用默認配置");
            }

        }

        
    private void reBuildWeb(File file)
        
    {
            
    try
            
    {
                file.createNewFile();
                FileOutputStream fos
    =new FileOutputStream(file);
                PrintStream sp
    =new PrintStream(fos);
                sp.println(
    "<html>");
                sp.println(
    "<head>");
                sp.println(
    "<title>Erik'簡單Web服務器</title>");
                sp.println(
    "</head>");
                sp.println(
    "<body>");
                sp.println(
    "<div align="+"center"+">服務器已經成功運行 </div>");
                sp.println(
    "</body>");
                sp.println(
    "</html>");
                sp.close();

            }

            
    catch (Exception ex)
            
    {
                ex.printStackTrace();
            }

        }

    }

    Request.java

    package htmlbrowser;

    import java.io.InputStream;

    public class Request
    {
        
    public Request()
        
    {

        }


        
    private InputStream input;
        
    private String uri;
        
    public Request(InputStream input)
        
    {
            
    this.input = input;
        }


        
    public void parse()//取得請求信息
        {
            StringBuffer request 
    = new StringBuffer(2048);
            
    int i;
            
    byte[] buffer = new byte[2048];
            
    try
            
    {
                i 
    = input.read(buffer);
            }

            
    catch (Exception ex)
            
    {
                ex.printStackTrace();
                i 
    = -1;
            }

            
    for (int j = 0; j < i; j++)
            
    {
                request.append((
    char) buffer[j]);
            }

            System.out.println(request.toString());
            uri 
    = parseUri(request.toString());

            System.out.println(
    "用戶請求:"+this.getUri());

        }


        
    private String parseUri(String requestString)//分析請求信息,并返回
        {
            
    int index1, index2;
            index1 
    = requestString.indexOf(" ");

            
    if (index1 != -1)
            
    {
                index2 
    = requestString.indexOf(" ", index1 + 1);

                
    if (index2 > index1)
                
    {
                    
    return requestString.substring(index1 + 1, index2);
                }


            }

            
    return null;
        }


        
    public String getUri()
        
    {
            
    if (uri.compareTo("/")==0)
            
    {
                uri
    ="/index.htm";
            }

            
    if (uri.indexOf(".")==-1)
            
    {
                uri
    +=".htm";
            }

            
    return uri;
        }

    }

    Response.java

    package htmlbrowser;

    import java.io.OutputStream;
    import java.io.IOException;
    import java.io.FileInputStream;
    import java.io.File;

    public class Response
    {

        
    private static final int BUFFER_SIZE = 1024;
        Request request;
        OutputStream output;

        
    public Response(OutputStream output)
        
    {
            
    this.output = output;

        }


        
    public void setRequest(Request request)
        
    {
            
    this.request = request;
        }


        
    public void sendStaticResource()//發送請求資源
                throws IOException
        
    {
            
    byte[] bytes = new byte[BUFFER_SIZE];
            FileInputStream fis 
    = null;
            
    try
            
    {

                File file 
    = new File(HttpServer.WEB_ROOT, request.getUri());

                
    if (file.exists())
                
    {
                    System.out.println(
    "開始發送用戶請求資源");
                    fis 
    = new FileInputStream(file);
                    
    int ch = fis.read(bytes, 0, BUFFER_SIZE);
                    
    while (ch != -1)
                    
    {
                        output.write(bytes, 
    0, ch);
                        ch 
    = fis.read(bytes, 0, BUFFER_SIZE);
                    }

                    System.out.println(
    "發送完畢!");
                }

                
    else
                
    {
                    System.out.println(
    "用戶請求的資源不存在");
                    String errorMessage 
    = "HTTP/1.1 404 File Not Found\r\n" +
                                          
    "Content-Type:text/html\r\n" +
                                          
    "\r\n" +
                                          
    "<hl>File Not Found</hl>";
                    output.write(errorMessage.getBytes());
                }

            }

            
    catch (Exception ex)
            
    {
                ex.printStackTrace();
                System.out.println(
    "獲取請求資源錯誤,請檢查本地資源設置!");
                System.exit(
    1);
            }

            
    if (fis != null)
            
    {
                fis.close();
            }

        }


    }

     

    轉載:http://www.javaresearch.org/code/thread.jsp?column=721&thread=35194

    主站蜘蛛池模板: 亚洲AV第一成肉网| 久久亚洲免费视频| 四虎国产精品免费久久影院| 国产精品免费网站| 99re6热视频精品免费观看| a级成人毛片免费视频高清| 一级做a免费视频观看网站| 人成电影网在线观看免费| 丁香六月婷婷精品免费观看| 特色特黄a毛片高清免费观看 | 男女超爽刺激视频免费播放 | 亚洲精品无码日韩国产不卡av| 亚洲欧洲另类春色校园网站| 在线观看片免费人成视频无码| 中文字幕在线视频免费| 国产免费人成视频尤勿视频| 国产一级婬片A视频免费观看| 91免费国产视频| 亚在线观看免费视频入口| 亚洲香蕉免费有线视频| 无码国产精品一区二区免费式影视 | 亚洲精品国产专区91在线| 亚洲国产精品日韩在线| 亚洲偷自精品三十六区| 亚洲AV成人一区二区三区观看| 美女黄色免费网站| baoyu777永久免费视频| 99视频免费播放| 欧亚精品一区三区免费| 四虎免费永久在线播放| 久久精品国产亚洲综合色| 亚洲性猛交xx乱| 亚洲av日韩av永久无码电影| 野花视频在线官网免费1| 男人天堂免费视频| 97免费人妻无码视频| 四虎永久免费地址在线网站| 亚洲人成精品久久久久| 亚洲国产美女精品久久久久| 亚洲精品无码日韩国产不卡av| 亚洲免费一区二区|