⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 webserver.java

📁 一个简单的HTTP服务器和HTTP客户端程序 HTTP客户端(即浏览器)只支持显示标准HTML
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
     */
    public void setTaInfo(JTextArea taInfo)
    {
        this.taInfo = taInfo;
    }

    /**
     * 返回当前用户数目
     * @return
     */
    public int getUserNumber()
    {
        return userNumber;
    }

    
    /**
     * 单独为每个一个用户打开一个线程 处理每个用户的请求服务
     */
    class ServerThread extends Thread
    {
        /**
         * 连接Web浏览器的socket
         */
        Socket client;

        /**
         * 目的IP地址
         */
        String destIP = null;
        
        /**
         * 用户查找的信息
         */
        String searchInfo="";

        /**
         * 客户机端口号
         */
        int destport = 80;

        /**
         * 构造函数
         * @param client
         */
        public ServerThread(Socket client)
        {
            this.client = client;
            //获取IP
            destIP = client.getInetAddress().toString();
            //获取端口
            destport = client.getPort();
        }

        /**
         * 提供WEB服务的线程体
         * 
         * 功能:接受用户请求,并作出响应
         */
        public void run()//线程体
        {
            try
            {
                //输出流
                PrintStream outstream = new PrintStream(client
                        .getOutputStream());
                //输入流
                DataInputStream instream = new DataInputStream(client
                        .getInputStream());
                
                //读取Web浏览器提交的请求信息的第一行
                //比如:GET / HTTP/1.1
                //比如:GET /phoenixtv/79658522215710720/20060427/787308.shtml HTTP/1.1
                String inline = instream.readLine();
                
                // 判断该请求是否GET请求
                if (getrequest(inline))
                {
                    //获取请求的文件名
                    String filename = getRequestFileName(inline);
                    
                    //如果是搜索功能:/?后加搜索的字符串
                    if(filename.length()>0&&filename.charAt(0)=='?')
                    {
                        searchInDir(serverPath,filename.substring(1));
                        
                        outstream.println("HTTP /1.1 200 OK");
                        outstream.println("Content_Type:text/html");
                        outstream.println("Content_Length:" + searchInfo.length()+2);
                        outstream.println("");
                        outstream.println(searchInfo.replace('\\','/'));
                        outstream.flush();
                    }
                    else
                    {
                        //打开文件
                        File file = new File(serverPath, filename);
                    
                        //若文件存在,则将文件送给Web浏览器
                        if (file.exists())
                        {
                       //发送响应的头部
                        outstream.println("HTTP/1.1 200 OK");
                        outstream.println("MIME_version:1.0");
                        outstream.println("Content_Type:text/htm1");
                        int len = (int) file.length();//发送文件长度
                        outstream.println("Content_Length:" + len);
                        outstream.println("");
                        sendfile(outstream,file);//发送文件
                        outstream.flush();
                        } else
                        {//文件不存在时,则发送找不到该文件的提示
                        Date data=new Date();
                        String notfound = "<html><head><title>File Not Found</title></head><body><hl>Error 404-File not found</hl>" +
                        		"<br><br><br><li>from browser of <b>CQU</b><br>"+data.toString()+"</body></html>";
                        outstream.println("HTTP /1.1 404 no found");
                        outstream.println("Content_Type:text/html");
                        outstream.println("Content_Length:" + notfound.length()+2);
                        outstream.println("");
                        outstream.println(notfound);
                        outstream.flush();
                        }
                    }
                }
                long m1 = 1;
                while (m1 < 11100000)
                {
                    m1++;
                } // 延时
                client.close();
            } catch (IOException e)
            {
                System.out.println("Exception:" + e);
            }
        }        
        /**
         * 获取请求类型是否为GET
         */
        boolean getrequest(String s)
        {
            info("客户 " + this.destIP + "请求文件" + s);
            if (s.length() > 0)
            {
                if (s.substring(0, 3).equalsIgnoreCase("GET"))
                    return true;
            }
            return false;
        }
        /**
         * 在一个目录中查找
         * @param dir
         */
        public synchronized void searchInDir(String dir,String title)
        {
            try
            {
                File fileDir = new File(dir);

                if (fileDir.isDirectory())
                {             
                    String[] str = fileDir.list();
                    for (int i = 0; i < str.length; i++)
                    {
                        searchInDir(dir+"\\"+str[i],title);
                    }
                }
                else
                {
                    int index=searchInFile(fileDir,title);
                    if(index>=0)
                    {
                       String item="<a href=http:/"+dir.replace(serverPath,client.getLocalAddress().toString())+">"+title+"</a><br>";
                       this.searchInfo+=item;
                    }
                    else if(index==-2)
                    {
                        return ; 
                    }
                }
            } catch (Exception e)
            {
                e.printStackTrace();
            }
        }
        /**
         * 在HTML文件内容和标题中同时查找字符串
         * @param file
         * @param title
         * @return
         */
        public synchronized  int searchInFile(File file,String title)
        {
            try
            {
                FileReader fr = new FileReader(file);
                BufferedReader br = new BufferedReader(fr);
                String content = "";
                String aline;
                while ((aline = br.readLine()) != null)
                    content += (aline + '\n');

                int index=content.indexOf(title);
                br.close();
                fr.close();
                br = null;
                fr = null;

                return index;
            } catch (Exception ee)
            {
                ee.printStackTrace();
                return -2;
            }
        }

        /*
         * 获取要访问的文件名
         */
        String getRequestFileName(String s)
        {
            String f = s.substring(s.indexOf('/') + 1);
            try
            {
                int len = f.indexOf(' ');
                if (f.charAt(0) == '/')
                    f = f.substring(1);
                if (len != -1)
                    f = f.substring(0, len);
            }catch (IndexOutOfBoundsException e)
            {
                error("无法从字符串" + s + "中获取文件名.");
            }
            if (f.equals(""))
                f = "index.html";

            return f;
        }

        /*
         * 把指定文件发送给Web浏览器
         */
        void sendfile(PrintStream outs, File file)
        {
            try
            {
                DataInputStream in = new DataInputStream(new FileInputStream(
                        file));

                int len = (int) file.length();
                byte buf[] = new byte[len];
                in.readFully(buf);
                outs.write(buf, 0, len);
                outs.flush();
                in.close();
                info("客户 " + this.destIP + "请求文件" + file + "成功!");
            } catch (IOException e)
            {
                error("发送文件" + file + "给客户" + this.destIP + "发生错误错误.");
                // System.exit(1);
            }
        }
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -