静态web服务器(核心代码)

private void selectButtonActionPerformed(java.awt.event.ActionEvent evt) {                                            
// TODO add your handling code here:
   
    String temp=null;
    String s=null;
    jfc=new JFileChooser();                                            //文件选择
    int a=jfc.showOpenDialog(this);
    if(a==JFileChooser.APPROVE_OPTION)
    {
        selectedFile=jfc.getSelectedFile();
        temp=selectedFile.getPath();                                  //抽象路径名转换为一个路径名字符串
        pathField.setText(temp);                                           //显示路径  
    }                                           

}   


private void stopButtonActionPerformed(java.awt.event.ActionEvent evt) {                                          
// TODO add your handling code here:
   
    try{
        serversocket.close();
    }catch(IOException e)
    {
        TextArea.append("Closing server failed!/n");
    }
   
}                                         


         private int getPort(){                                   //获取服务器所对应的端口
      
        int temp;
        temp=Integer.parseInt(portField.getText());
        return temp;
  
    } 
  
    class ListenThread extends Thread{
       
        public void run(){
        try{
            serversocket=new ServerSocket(getPort());    //建立一个新的服务器端套接字
            TextArea.append("Server is listening....../n");
            while(true)
            {
                socket=serversocket.accept();
                clientCount++;
                new clientThread(socket,clientCount).start();           
            }     
        }catch(IOException e){
            TextArea.append("The connection is failed!error from:serversocket/n");
        } 
        }
    }
   
    class clientThread extends Thread{
        public Socket client;
        public int count;
        public String clientHost;
        public int clientPort;
        public boolean get;
        public boolean post;
       
        public clientThread(Socket socket,int clientCount){
            client=socket;
            count=clientCount;        //连接数
            clientHost=null;          //客户端的地址
            clientPort=0;             //客户端建立连接的端口
            get=false;
            post=false;
        }
       
        public void run(){
        
            String firstLineInfor=null;
            String optionFileName=null;
            String filePath=null;
            boolean result=false;
               
                //获取客户端的地址
                clientHost = socket.getInetAddress().toString();
                //获取客户端建立连接的端口
                clientPort = socket.getPort();
                //显示当前连接数以及连接的主机地址以及端口
                TextArea.append("Connection" + count + ":  Host: " + clientHost + "  Port: " + clientPort + "/n");
                 //获取客户端请求的信息流
                 
                firstLineInfor=getFirstLineRequestInfor();
               
                if(firstLineInfor!=null)
                {
                    get=isGetWay(firstLineInfor);
                    post=isPostWay(firstLineInfor);
               
                    optionFileName=getOptionFileName(firstLineInfor,get,post);
               
                    filePath=pathField.getText().concat(optionFileName);  
                    File optionFile=new File(filePath);
               
                    result=sendMessageHead(optionFile);
                   
                    if(result)
                    {
                        sendFile(optionFile);
                    
                    }
                    else
                    {
                        TextArea.append("The business is unsusessful!");
                       
                    }
                    try{
                       client.close();
                    }catch(IOException e)
                    {
                        e.printStackTrace();
                    }
                }
        
        }
     
    //判断是否为get请求
   
    public boolean isGetWay(String s){    
      
        //子串匹配,大小不计
        if(s.substring(0,2).equalsIgnoreCase("GET"))      
            return true;
        else
            return false;
       
    }
   
    //判断是否为post请求
   
    public boolean isPostWay(String s){ 
       
        if(s.substring(0,3).equalsIgnoreCase("POST"))
            return true;
        else
            return false;
       
    }
   
    //获取请求报文第一行的信息,并以字符串的形式返回
   
    public String getFirstLineRequestInfor()
    {
        try{
            BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));   
            String s=br.readLine();
            return s;
        }catch(IOException e)
        {
            TextArea.append("getFirstLineRequestInfor failed!/n");
        }
        return null;
           
       
     }
   
    //获得请求访问的文件名

    public String getOptionFileName(String firstLineInfor,boolean get,boolean post){   
       
        int beginIndex=0;
        String sub=null;
        String optionFileName=null;
       
        if(get==true&&post==false)
        {
            beginIndex=4;
        }
       
        if(get==false&&post==true)
        {
            beginIndex=5;
        }
       
        sub=firstLineInfor.substring(beginIndex,(firstLineInfor.length()-9));
       
        int index=sub.lastIndexOf("/");
        optionFileName=sub.substring(index,sub.length());
        optionFileName=optionFileName.replace('/','//');
   
        return optionFileName;
       
    }
   
    //发送应答报文头部信息
   
    public boolean sendMessageHead(File optionFile)
    {
        PrintWriter pw=null;
        try{
            pw=new PrintWriter(client.getOutputStream());
  
            if(optionFile.exists())
            {
                pw.write("HTTP/1.1 200 OK/n");
                pw.write("MIME-version: 1.0/n");
                pw.write("Content-type: test/html/n");
                pw.write("/n");
                pw.flush();
         
                return true;
            }
               
            else
            {
                pw.write("HTTP/1.1 404 NOT FOUND");
                pw.write("/n");
                pw.flush();
                notFoundError();
                return false;
             }
        }catch(IOException e)
        {
            TextArea.append("sendMessageHead failed!/n");
        }
        return false;
    }
   
    //向客户端发送目标文件
   
    public void sendFile(File file){ 
       
        PrintWriter pw=null;
        BufferedReader br=null;
        String s=null;
               
        try{
            br=new BufferedReader(new InputStreamReader(new FileInputStream(file)));
            pw=new PrintWriter(client.getOutputStream());
           
            while((s=br.readLine())!=null)
            {
                pw.write(s);
                pw.write("/n");
            }  
            pw.flush();
            pw.close();
           
        }catch(IOException e){
            TextArea.append("sendFile failed!/n");
        }
    } 
    public void notFoundError()
    {
       
        PrintWriter pw=null;
        try{
            pw=new PrintWriter(client.getOutputStream());
            pw.write("<html>/n");
            pw.write("<head>/n");
            pw.write("<title>ERROR404</title>/n");
            pw.write("</head>/n");
            pw.write("<body>/n");
            pw.write("<h1>ERROR404---File not founnd</h1>/n");
            pw.write("</body>/n");
            pw.write("</html>/n");
            pw.flush();
        }catch(IOException e){
           TextArea.append("Display error file fialed!/n");
        }
       
     }
   
    } 

 

版权所有:Cynthia100。yanyanxiyang

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值