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

📄 httpserverhandler.java

📁 一个简单的visio程序。
💻 JAVA
字号:

package servlet.http;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import servlet.ServletConnection;
import java.net.URL;

import server.HttpServer;

public class HttpServerHandler
    implements Runnable, ServletConnection
 {

    public HttpServerHandler(HttpServer httpserver)
    {
        buf = new byte[512];
        server = httpserver;
        req.setSessionContext(httpserver.getSessionContext());
        req.setResponse(res);
    }

    public void run()
    {
        Socket socket1;
        while((socket1 = (Socket)server.getConnection()) != null) 
            try
            {
                socket = socket1;
                handleConnection(socket1);
                socket1.close();
            }
            catch(IOException ioexception)
            {
                ioexception.printStackTrace();
            }

    }

    
    protected void handleConnection(Socket socket1)
        throws IOException
    {
        
        req.init(this);
        res.init(this);
                
        
        while(req.next()) {
            
            res.next();
            if(req.getMajorVersion() < 1)
                res.printKeepAlive();
            else if(req.getMajorVersion() == 1) {
                
                MessageBytes messagebytes = req.getRequestPath();
                if(messagebytes.startsWith(PREFIX)) {
                    res.printKeepAlive();
                    res.setProtocol("HTTP/1.0");
                    res.setHeader("Server", server.name);
                }else if (req.getMethod().equals("GET")){
                    String realPath = server.getRealPath(req.getRequestURI());
                    doGet(realPath);                
                    req.finish();
                    res.finish();
                    return;
                }
                
            }else{
                res.setProtocol("HTTP/1.0");
                res.setHeader("Server", server.name);
                res.sendError(505);
                return;
            }
            res.setKeepAlive(req.getKeepAlive());
            try {
                sendResponse(req, res);
            }catch(Exception exception) {
                if(res.getTotalBytes() == 0)
                    try
                    {
                        res.sendError(500);
                    }
                    catch(IOException ex) {}
                exception.printStackTrace();
            }
            
            req.finish();
            res.finish();
            if(!res.getKeepAlive()) {
                return;
            }
        }

    }   // end of handleConnection.

    protected void sendResponse(HttpRequest httprequest, HttpResponse httpresponse)
        throws ServletException, IOException {
            
        MessageBytes messagebytes = httprequest.getRequestPath();
        if(messagebytes.startsWith(PREFIX)) 
        {
            String s = parsePath(messagebytes, httprequest);
            if(s != null) {
                Servlet servlet = server.getServlet(s);
                if(servlet != null)
                    if(servlet instanceof SingleThreadModel)
                    {
                        synchronized(servlet) 
                        {
                            servlet.service(httprequest, httpresponse);
                        }
                        return;
                    }
                    else
                    {
                        servlet.service(httprequest, httpresponse);
                        return;
                    }
                System.err.println("Servlet not found: " + s);
            }
        }
        else
        {
            String s1 = httprequest.getMethod();
            if(s1.equals("GET")) {
                return;
            }else if (s1.equals("HEAD")) {
                httpresponse.sendError(403, "Will not serve files, only servlets");
                return;
            }
        }
        httpresponse.sendError(404);
    }

    protected  void doGet(String realPath) throws IOException {
        
        File targ = new File(realPath);
        if (targ.isDirectory()) {
            File ind = new File(targ, "index.html");
            if (ind.exists()) {
                targ = ind;
            }
        }
        PrintStream ps = new PrintStream(socket.getOutputStream());
        boolean OK = printHeaders(targ, ps);
        if (OK) {
            sendFile(targ, ps);
        } else {
            send404(targ, ps);
       }
       
    }   // end of doGet.
    
    protected String parsePath(MessageBytes messagebytes, HttpRequest httprequest) {
        
        byte abyte0[] = messagebytes.getBytes();
        int i = messagebytes.getOffset() + PREFIX_LEN;
        int j = messagebytes.getLength() - PREFIX_LEN;
        int k;
        for(k = i; k < i + j && abyte0[k] != 47; k++);
        if(k < i + j)
            httprequest.setPathInfo(abyte0, k, (i + j) - k);
        else
            k = i + j;
        String s = new String(abyte0, 0, i, k - i);
        i -= PREFIX_LEN;
        httprequest.setServletPath(abyte0, i, k - i);
        return s;
        
    }

    public String getServerName()
    {
        return server.host;
    }

    public int getServerPort()
    {
        return server.port;
    }

    public String getRemoteHost()
    {
        return socket.getInetAddress().getHostName();
    }

    public String getRemoteAddr()
    {
        return socket.getInetAddress().getHostAddress();
    }

    public String getRealPath(String s)
    {
        return server.getRealPath(s);
    }

    public InputStream getInputStream()
        throws IOException
    {
        return socket.getInputStream();
    }

    public OutputStream getOutputStream()
        throws IOException
    {
        return socket.getOutputStream();
    }

    protected HttpServer server;
    protected final HttpRequest req = new HttpRequest();
    protected final HttpResponse res = new HttpResponse();
    protected Socket socket;
    protected byte buf[];
    protected static String PREFIX;
    protected static int PREFIX_LEN;

    static 
    {
        PREFIX = "/servlet/";
        PREFIX_LEN = PREFIX.length();
    }
    
    
    /// add by Ligou
    
      boolean printHeaders(File targ, PrintStream ps) throws IOException {
        
          boolean ret = false;
          int rCode = 0;
          if (!targ.exists()) {
              //System.out.println("file = " + targ);  
              rCode = HTTP_NOT_FOUND;
              ps.print("HTTP/1.0 " + HTTP_NOT_FOUND + " not found");
              ps.write(EOL);
              ret = false;
          }  else {
              rCode = HTTP_OK;
              ps.print("HTTP/1.0 " + HTTP_OK+" OK");
              ps.write(EOL);
              ret = true;
//              return true;
              
          }
          //log("From " +server.getInetAddress().getHostAddress()+": GET " +

            //  targ.getAbsolutePath()+"-->"+rCode);
          ps.print("Server: Simple java");
          ps.write(EOL);
          ps.print("Date: " + (new java.util.Date()));
          ps.write(EOL);
          if (ret) {
              if (!targ.isDirectory()) {
                  ps.print("Content-length: "+targ.length());
                  ps.write(EOL);
                  ps.print("Last Modified: " + (new
                           java.util.Date(targ.lastModified())));
                  ps.write(EOL);
                  String name = targ.getName();
                  int ind = name.lastIndexOf('.');
                  String ct = null;
                  if (ind > 0) {
                      ct = (String) map.get(name.substring(ind));
                  }
                  if (ct == null) {
                      ct = "unknown/unknown";
                  }
                  ps.print("Content-type: " + ct);
                  ps.write(EOL);
              } else {
                  ps.print("Content-type: text/html");
                  ps.write(EOL);
              }
          }
          return ret;
      }

      void send404(File targ, PrintStream ps) throws IOException {
          ps.write(EOL);
          ps.write(EOL);
          ps.println("Not Found\n\n"+
                     "The requested resource was not found.\n");
      }

      void sendFile(File targ, PrintStream ps) throws IOException {
        
          InputStream is = null;
          ps.write(EOL);
          if (targ.isDirectory()) {
              /* here, we take advantage of the fact
               * that FileURLConnection will parse a directory
               * listing into HTML for us.
               */
              File ind = new File(targ, "index.html");
              if (ind.exists()) {
                  is = new FileInputStream(ind);
              } else {
                  URL u = new URL("file", "", targ.getAbsolutePath());
                  is = u.openStream();
              }
          } else {
              is = new FileInputStream(targ.getAbsolutePath());
          }

          try {
              int n;
              buf = new byte[2048];
              for (int i =0; i < 2048; i++) 
                  buf[i] = 0;
                  
              while ((n = is.read(buf)) > 0) {
                  ps.write(buf, 0, n);
              }
          } finally {
              is.close();
          }
      }

      static final byte[] EOL = {(byte)'\r', (byte)'\n' };
      public static final int HTTP_OK = 200;
      public static final int HTTP_NOT_FOUND = 404;
      
      
      static java.util.Hashtable map = new java.util.Hashtable();

      static {
          fillMap();
      }
      static void setSuffix(String k, String v) {
          map.put(k, v);
      }

      static void fillMap() {
          setSuffix("", "content/unknown");
          setSuffix(".uu", "application/octet-stream");
          setSuffix(".exe", "application/octet-stream");
          setSuffix(".ps", "application/postscript");
          setSuffix(".zip", "application/zip");
          setSuffix(".sh", "application/x-shar");
          setSuffix(".tar", "application/x-tar");
          setSuffix(".snd", "audio/basic");
          setSuffix(".au", "audio/basic");
          setSuffix(".wav", "audio/x-wav");
          setSuffix(".gif", "image/gif");
          setSuffix(".jpg", "image/jpeg");
          setSuffix(".jpeg", "image/jpeg");
          setSuffix(".htm", "text/html");
          setSuffix(".html", "text/html");
          setSuffix(".text", "text/plain");
          setSuffix(".c", "text/plain");
          setSuffix(".cc", "text/plain");
          setSuffix(".c++", "text/plain");
          setSuffix(".h", "text/plain");
          setSuffix(".pl", "text/plain");
          setSuffix(".txt", "text/plain");
          setSuffix(".java", "text/plain");
      }

    ///
}

⌨️ 快捷键说明

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