<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 沙漠中的魚 閱讀(1451) 評論(0)  編輯  收藏 所屬分類: 系統架構 、Java 、Java基礎

    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免费看图片| 亚洲乱码一区av春药高潮| 无码国产精品一区二区免费式影视 | 成人毛片18女人毛片免费视频未| 亚洲人成网站18禁止| 在线中文高清资源免费观看| 亚洲精品理论电影在线观看| 免费视频中文字幕| 美女羞羞免费视频网站| 久久久久一级精品亚洲国产成人综合AV区| 两个人看的www免费高清| 西西人体44rt高清亚洲| 日本三级2019在线观看免费| 精品亚洲永久免费精品| 亚洲国产成人久久三区| 亚洲成色999久久网站| 亚洲乳大丰满中文字幕| 免费看h片的网站| 在线亚洲v日韩v| 亚洲爆乳无码专区| 成人免费视频试看120秒| 久久成人国产精品免费软件| 午夜免费福利视频| 亚洲av成人无码网站…| 国产亚洲无线码一区二区| 日韩一区二区a片免费观看| 啦啦啦完整版免费视频在线观看| 亚洲AV综合永久无码精品天堂| 亚洲国产精品久久人人爱| 国产人成免费视频| 国产成人久久AV免费| 亚洲1区2区3区精华液| 亚洲人成网站在线在线观看| 亚洲狠狠成人综合网| 中文亚洲成a人片在线观看| 久久精品国产亚洲精品| 亚洲一区二区三区影院| 亚洲日本乱码在线观看|