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

📄 dynaserver.java

📁 精通RMI 这是RMI的入门基础 特别对刚开始学RMI的同胞们很有帮助
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
         {
            serverSocket = new ServerSocket(getPort(), getBackLog());
            serverSocket.setSoTimeout(SO_TIMEOUT);
         } catch (IOException e)
         {
            // Try port scanning
            portscan: if (getPortScan())
            {
               debug(getPort()+" already in use. Trying port scanning");
               StringTokenizer portTokens = new StringTokenizer(PORTS,",");
               while (portTokens.hasMoreTokens())
               {
                  String portString = portTokens.nextToken();
                  int port = new Integer(portString).intValue();
                  debug("Trying port "+port);
                  try
                  {
                     serverSocket = new ServerSocket(port, getBackLog());
                     serverSocket.setSoTimeout(SO_TIMEOUT);
                     setPort(serverSocket.getLocalPort());
                     debug("Started on port "+getPort());
                     break portscan;
                  } catch (BindException exc)
                  {
                     // Ignore, try next port
                  }
               }
               // Will never get here as last port to try is 0, which always works..
               
               // Ah what the heck.. just in case..
               throw new BindException("Could not start listener. Port(s) already taken");
            }
         }
         
         new Thread(this).start();
      }
   
      public void run()
      {
         try
         {
            while (isRunning())
            {
               try
               {
                  addRequest(serverSocket.accept());
               } catch (InterruptedIOException e)
               {
                  // Ignore - normal because of timeout
               }
            }
            debug("Listener stopped");
         } catch (Throwable e)
         {
            e.printStackTrace();
            stop();
         } finally
         {
            try
            {
               serverSocket.close();
            } catch (IOException exc)
            {
               // Ignore
            }
            
            // Notify thread doing a stop() call
            synchronized(DynaServer.this)
            {
               DynaServer.this.notifyAll();
            }
         }
      }
   }
   
   class RequestHandler
      implements Runnable
   {
      RequestHandler()
      {
         new Thread(this).start();
      }
            
      public void run()
      {
         try
         {
            while (isRunning())
            {
               // Get requesting socket
               Socket socket;
               try
               {
                  socket = getRequest();
               } catch (IllegalStateException e)
               {
                  // Server was stopped
                  break;
               }
            
               DataOutputStream out = null;
               BufferedReader in = null;
               String file = "";
               try
               {
                  // Create in/out streams
                  out = new DataOutputStream(socket.getOutputStream());
                  in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            
                  // Get request
                  file = getPath(in);
               
                  // Get URL to resource
                  URL url = getURL(file);
               
                  // Get bytes for file
                  byte[] bytes = getBytes(url);
               
                  // Send bytes
                  sendResponse(out, getMimeType(file), bytes);
               
               } catch (FileNotFoundException e)
               {
                  sendError(out, "File not found:"+file);
               } catch (IOException e)
               {
                  sendError(out, "Error reading file:"+e.getMessage());
               } finally
               {
                  // Close request
                  try
                  {
                     out.close();
                     in.close();
                     socket.close();
                  } catch (IOException e)
                  {
                     // Ignore
                  }
               }
            }
         } catch (Throwable e)
         {
            // Something went terribly wrong and the handler is lost
            debug(e.getMessage());
            
            // Create a new one in its place
            debug("Creating new request handler");
            new RequestHandler();
         } finally
         {
            debug("Handler stopped");
         }
      }
            
      private String getPath(BufferedReader in)
         throws IOException
      {
         String line = in.readLine();
         
         int idx = line.indexOf(" ")+1;
         return line.substring(idx+1,line.indexOf(" ",idx)); // The file minus the leading /
      }
      
      private URL getURL(String path)
         throws FileNotFoundException
      {
         if (path.endsWith(".class")) // Class
         {
            String className = path.substring(0, path.length()-6).replace('/','.');
         
            // Try getting class
            URL clazzUrl = null;
            for (int i = 0; i < classLoaders.size(); i++)
            {
               try
               {
                  Class clazz = ((ClassLoader)classLoaders.get(i)).loadClass(className);
                  clazzUrl = clazz.getProtectionDomain().getCodeSource().getLocation();
                  if (clazzUrl.getFile().endsWith(".jar"))
                     clazzUrl = new URL("jar:"+clazzUrl+"!/"+path);
                  else
                     clazzUrl = new URL(clazzUrl, path);
                  
                  return clazzUrl;
               } catch (ClassNotFoundException e)
               {
                  // Ignore (normal)
               } catch (MalformedURLException e)
               {
                  throw new FileNotFoundException("Could not create URL for "+path);
               }
            }
         
            // We don't have this class
            throw new FileNotFoundException("Class file not found:"+className);
         } else // Resource
         {
            // Try getting resource
            URL resourceUrl = null;
            for (int i = 0; i < classLoaders.size(); i++)
            {
               resourceUrl = ((ClassLoader)classLoaders.get(i)).getResource(path);
            
               if (resourceUrl != null)
                  return resourceUrl;
            }
         
            // We don't have this file
            throw new FileNotFoundException("File not found:"+path);
         }
      }
      
      private byte[] getBytes(URL url)
         throws IOException
      {
         debug("Retrieving "+url.toString());
         
         InputStream in = new BufferedInputStream(url.openStream());
         ByteArrayOutputStream out = new ByteArrayOutputStream();
         int data;
         while ((data = in.read()) != -1)
         {
            out.write(data);
         }
         return out.toByteArray();
      }
      
      private void sendResponse(DataOutputStream out, String mimeType, byte[] bytes)
         throws IOException
      {
            // Send bytecodes in response (assumes HTTP/1.0 or later)
            out.writeBytes("HTTP/1.0 200 OK\r\n");
            out.writeBytes("Content-Length: " + bytes.length +
                           "\r\n");
            out.writeBytes("Content-Type: "+mimeType+"\r\n\r\n");
            out.write(bytes);
            out.flush();
      }
      
      private void sendError(DataOutputStream out, String message)
      {
         if (out == null)
            return;
            
         debug("Send error page:"+message);
   
         try
         {
            // Write out error response
            out.writeBytes("HTTP/1.0 400 " + message + "\r\n");
            out.writeBytes("Content-Type: text/html\r\n\r\n");
            out.writeBytes("<HTML><BODY><H1>Error</H1><B>"+message+"</B></BODY></HTML>");
            out.flush();
         } catch (IOException ex)
         {
            // Ignore
         }
      }
   }
}

⌨️ 快捷键说明

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