100個Java經典例子(轉)

https://www.iteye.com/blog/larry1001-1619176

package test41;  
  
import java.io.*;  
/** 
 * Title: 運行系統命令 
 * Description:運行一個系統的命令,演示使用Runtime類。 
 * Filename: CmdExec.java 
 */  
public class CmdExec {  
/** 
 *方法說明:構造器,運行系統命令 
 *輸入參數:String cmdline 命令字符 
 *返回類型: 
 */  
  public CmdExec(String cmdline) {  
    try {  
     String line;  
     //運行系統命令  
     Process p = Runtime.getRuntime().exec(cmdline);  
     //使用緩存輸入流獲取屏幕輸出。  
     BufferedReader input =   
       new BufferedReader  
         (new InputStreamReader(p.getInputStream()));  
     //讀取屏幕輸出  
     while ((line = input.readLine()) != null) {  
       System.out.println("java print:"+line);  
       }  
     //關閉輸入流  
     input.close();  
     }   
    catch (Exception err) {  
     err.printStackTrace();  
     }  
   }  
/** 
 *方法說明:主方法 
 *輸入參數: 
 *返回類型: 
 */  
public static void main(String argv[]) {  
   new CmdExec("myprog.bat");  
  }  
}  
view plain
package test43;  
  
import java.io.*;  
import java.net.*;   
/** 
 * Title: 簡單服務器客戶端 
 * Description: 本程序是一個簡單的客戶端,用來和服務器連接 
 * Filename: SampleClient.java 
 */  
public class SampleClient {  
    public static void main(String[] arges) {  
        try {  
            // 獲取一個IP。null表示本機  
            InetAddress addr = InetAddress.getByName(null);  
            // 打開8888端口,與服務器建立連接  
            Socket sk = new Socket(addr, 8888);  
            // 緩存輸入  
            BufferedReader in = new BufferedReader(new InputStreamReader(sk  
                    .getInputStream()));  
            // 緩存輸出  
            PrintWriter out = new PrintWriter(new BufferedWriter(  
                    new OutputStreamWriter(sk.getOutputStream())), true);  
            // 向服務器發送信息  
            out.println("你好!");  
            // 接收服務器信息  
            System.out.println(in.readLine());  
        } catch (Exception e) {  
            System.out.println(e);  
        }  
    }  
}  

view plain
package test43;  
  
import java.net.*;  
import java.io.*;  
/** 
 * Title: 簡單服務器服務端 
 * Description: 這是一個簡單的服務器端程序 
 * Filename: SampleServer.java 
 */  
public class SampleServer {  
    public static void main(String[] arges) {  
        try {  
            int port = 8888;  
            // 使用8888端口創建一個ServerSocket  
            ServerSocket mySocket = new ServerSocket(port);  
            // 等待監聽是否有客戶端連接  
            Socket sk = mySocket.accept();  
            // 輸入緩存  
            BufferedReader in = new BufferedReader(new InputStreamReader(sk  
                    .getInputStream()));  
            // 輸出緩存  
            PrintWriter out = new PrintWriter(new BufferedWriter(  
                    new OutputStreamWriter(sk.getOutputStream())), true);  
            // 打印接收到的客戶端發送過來的信息  
            System.out.println("客戶端信息:" + in.readLine());  
            // 向客戶端回信息  
            out.println("你好,我是服務器。我使用的端口號: " + port);  
        } catch (Exception e) {  
            System.out.println(e);  
        }  
    }  
}  

view plain
package test44;  
// 文件名:moreServer.java  
import java.io.*;  
import java.net.*;  
/** 
 * Title: 多線程服務器 
 * Description: 本實例使用多線程實現多服務功能。 
 * Filename:  
 */  
class moreServer  
{  
 public static void main (String [] args) throws IOException  
 {  
   System.out.println ("Server starting...\n");   
   //使用8000端口提供服務  
   ServerSocket server = new ServerSocket (8000);  
   while (true)  
   {  
    //阻塞,直到有客戶連接  
     Socket sk = server.accept ();  
     System.out.println ("Accepting Connection...\n");  
     //啓動服務線程  
     new ServerThread (sk).start ();  
   }  
 }  
}  
//使用線程,爲多個客戶端服務  
class ServerThread extends Thread  
{  
 private Socket sk;  
   
 ServerThread (Socket sk)  
 {  
  this.sk = sk;  
 }  
//線程運行實體  
 public void run ()  
 {  
  BufferedReader in = null;  
  PrintWriter out = null;  
  try{  
    InputStreamReader isr;  
    isr = new InputStreamReader (sk.getInputStream ());  
    in = new BufferedReader (isr);  
    out = new PrintWriter (  
           new BufferedWriter(  
            new OutputStreamWriter(  
              sk.getOutputStream ())), true);  
  
    while(true){  
      //接收來自客戶端的請求,根據不同的命令返回不同的信息。  
      String cmd = in.readLine ();  
      System.out.println(cmd);  
      if (cmd == null)  
          break;  
      cmd = cmd.toUpperCase ();  
      if (cmd.startsWith ("BYE")){  
         out.println ("BYE");  
         break;  
      }else{  
        out.println ("你好,我是服務器!");  
      }  
    }  
    }catch (IOException e)  
    {  
       System.out.println (e.toString ());  
    }  
    finally  
    {  
      System.out.println ("Closing Connection...\n");  
      //最後釋放資源  
      try{  
       if (in != null)  
         in.close ();  
       if (out != null)  
         out.close ();  
        if (sk != null)  
          sk.close ();  
      }  
      catch (IOException e)  
      {  
        System.out.println("close err"+e);  
      }  
    }  
 }  
}  

view plain
package test44;  
  
//文件名:SocketClient.java  
import java.io.*;  
import java.net.*;  
  
class SocketThreadClient extends Thread {  
    public static int count = 0;  
  
    // 構造器,實現服務  
    public SocketThreadClient(InetAddress addr) {  
        count++;  
        BufferedReader in = null;  
        PrintWriter out = null;  
        Socket sk = null;  
        try {  
            // 使用8000端口  
            sk = new Socket(addr, 8000);  
            InputStreamReader isr;  
            isr = new InputStreamReader(sk.getInputStream());  
            in = new BufferedReader(isr);  
            // 建立輸出  
            out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sk  
                    .getOutputStream())), true);  
            // 向服務器發送請求  
            System.out.println("count:" + count);  
            out.println("Hello");  
            System.out.println(in.readLine());  
            out.println("BYE");  
            System.out.println(in.readLine());  
  
        } catch (IOException e) {  
            System.out.println(e.toString());  
        } finally {  
            out.println("END");  
            // 釋放資源  
            try {  
                if (in != null)  
                    in.close();  
                if (out != null)  
                    out.close();  
                if (sk != null)  
                    sk.close();  
            } catch (IOException e) {  
            }  
        }  
    }  
}  
  
// 客戶端  
public class SocketClient {  
    @SuppressWarnings("static-access")  
    public static void main(String[] args) throws IOException,  
            InterruptedException {  
        InetAddress addr = InetAddress.getByName(null);  
        for (int i = 0; i < 10; i++)  
            new SocketThreadClient(addr);  
        Thread.currentThread().sleep(1000);  
    }  
}  

view plain
package test45;  
  
import java.net.*;  
import java.io.*;  
/** 
 * Title: 使用SMTP發送郵件 
 * Description: 本實例通過使用socket方式,根據SMTP協議發送郵件 
 * Copyright: Copyright (c) 2003 
 * Filename: sendSMTPMail.java 
 */  
public class sendSMTPMail {  
/** 
 *方法說明:主方法 
 *輸入參數:1。服務器ip;2。對方郵件地址 
 *返回類型: 
 */   
  
    public static void main(String[] arges) {  
        if (arges.length != 2) {  
            System.out.println("use java sendSMTPMail hostname | mail to");  
            return;  
        }  
        sendSMTPMail t = new sendSMTPMail();  
        t.sendMail(arges[0], arges[1]);  
    }  
/** 
 *方法說明:發送郵件 
 *輸入參數:String mailServer 郵件接收服務器 
 *輸入參數:String recipient 接收郵件的地址 
 *返回類型: 
 */  
    public void sendMail(String mailServer, String recipient) {  
        try {  
            // 有Socket打開25端口  
            Socket s = new Socket(mailServer, 25);  
            // 緩存輸入和輸出  
            BufferedReader in = new BufferedReader(new InputStreamReader(s  
                    .getInputStream(), "8859_1"));  
            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s  
                    .getOutputStream(), "8859_1"));  
            // 發出“HELO”命令,表示對服務器的問候  
            send(in, out, "HELO theWorld");  
            // 告訴服務器我的郵件地址,有些服務器要校驗這個地址  
            send(in, out, "MAIL FROM: <[email protected]>");  
            // 使用“RCPT TO”命令告訴服務器解釋郵件的郵件地址  
            send(in, out, "RCPT TO: " + recipient);  
            // 發送一個“DATA”表示下面將是郵件主體  
            send(in, out, "DATA");  
            // 使用Subject命令標註郵件主題  
            send(out, "Subject: 這是一個測試程序!");  
            // 使用“From”標註郵件的來源  
            send(out, "From: riverwind <[email protected]>");  
            send(out, "\n");  
            // 郵件主體  
            send(out, "這是一個使用SMTP協議發送的郵件!如果打擾請刪除!");  
            send(out, "\n.\n");  
            // 發送“QUIT”端口郵件的通訊  
            send(in, out, "QUIT");  
            s.close();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
/** 
 *方法說明:發送信息,並接收回信 
 *輸入參數: 
 *返回類型: 
 */  
    public void send(BufferedReader in, BufferedWriter out, String s) {  
        try {  
            out.write(s + "\n");  
            out.flush();  
            System.out.println(s);  
            s = in.readLine();  
            System.out.println(s);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
/** 
 *方法說明:重載方法。向socket寫入信息 
 *輸入參數:BufferedWriter out 輸出緩衝器 
 *輸入參數:String s 寫入的信息 
 *返回類型: 
 */  
 public void send(BufferedWriter out, String s) {  
   try {  
      out.write(s + "\n");  
      out.flush();  
      System.out.println(s);  
      }  
   catch (Exception e) {  
      e.printStackTrace();  
      }  
   }  
}  

view plain
package test46;  
import java.io.*;  
import java.net.*;  
/** 
 * Title: SMTP協議接收郵件 
 * Description: 通過Socket連接POP3服務器,使用SMTP協議接收郵件服務器中的郵件 
 * Filename:  
 */  
class POP3Demo  
{  
/** 
 *方法說明:主方法,接收用戶輸入 
 *輸入參數: 
 *返回類型: 
 */  
  @SuppressWarnings("static-access")  
public static void main(String[] args){  
    if(args.length!=3){  
     System.out.println("USE: java POP3Demo mailhost user password");  
    }  
    new POP3Demo().receive(args[0],args[1],args[2]);  
  }  
/** 
 *方法說明:接收郵件 
 *輸入參數:String popServer 服務器地址 
 *輸入參數:String popUser 郵箱用戶名 
 *輸入參數:String popPassword 郵箱密碼 
 *返回類型: 
 */  
  public static void receive (String popServer, String popUser, String popPassword)  
  {  
   String POP3Server = popServer;  
   int POP3Port = 110;  
   Socket client = null;  
   try  
   {  
     // 創建一個連接到POP3服務程序的套接字。  
     client = new Socket (POP3Server, POP3Port);  
     //創建一個BufferedReader對象,以便從套接字讀取輸出。  
     InputStream is = client.getInputStream ();  
     BufferedReader sockin;  
     sockin = new BufferedReader (new InputStreamReader (is));  
     //創建一個PrintWriter對象,以便向套接字寫入內容。  
     OutputStream os = client.getOutputStream ();  
     PrintWriter sockout;  
     sockout = new PrintWriter (os, true); // true for auto-flush  
     // 顯示POP3握手信息。  
     System.out.println ("S:" + sockin.readLine ());  
       
     /*--   與POP3服務器握手過程   --*/       
      System.out.print ("C:");  
      String cmd = "user "+popUser;  
      // 將用戶名發送到POP3服務程序。  
      System.out.println (cmd);  
      sockout.println (cmd);  
      // 讀取POP3服務程序的迴應消息。  
      String reply = sockin.readLine ();  
      System.out.println ("S:" + reply);  
  
      System.out.print ("C:");  
      cmd = "pass ";  
      // 將密碼發送到POP3服務程序。  
      System.out.println(cmd+"*********");  
      sockout.println (cmd+popPassword);  
      // 讀取POP3服務程序的迴應消息。  
      reply = sockin.readLine ();  
      System.out.println ("S:" + reply);  
        
             
      System.out.print ("C:");  
      cmd = "stat";  
      // 獲取郵件數據。  
      System.out.println(cmd);  
      sockout.println (cmd);  
      // 讀取POP3服務程序的迴應消息。  
      reply = sockin.readLine ();  
      System.out.println ("S:" + reply);  
      if(reply==null) return;  
      System.out.print ("C:");  
      cmd = "retr 1";  
      // 將接收第一豐郵件命令發送到POP3服務程序。  
      System.out.println(cmd);  
      sockout.println (cmd);  
        
      // 輸入了RETR命令並且返回了成功的迴應碼,持續從套接字讀取輸出,   
      // 直到遇到<CRLF>.<CRLF>。這時從套接字讀出的輸出就是郵件的內容。  
      if (cmd.toLowerCase ().startsWith ("retr") &&  
        reply.charAt (0) == '+')  
        do  
        {  
          reply = sockin.readLine ();  
          System.out.println ("S:" + reply);  
          if (reply != null && reply.length () > 0)  
            if (reply.charAt (0) == '.')  
              break;  
        }  
        while (true);  
      cmd = "quit";  
      // 將命令發送到POP3服務程序。  
      System.out.print (cmd);  
      sockout.println (cmd);       
   }  
   catch (IOException e)  
   {  
     System.out.println (e.toString ());  
   }  
   finally  
   {  
     try  
     {  if (client != null)  
          client.close ();  
     }  
     catch (IOException e)  
     {  
     }  
   }  
  }  
}  

view plain
package test47;  
  
import java.util.*;  
import javax.mail.*;  
import javax.mail.internet.*;  
import javax.activation.*;  
  
/** 
 * Title: 使用javamail發送郵件 Description: 演示如何使用javamail包發送電子郵件。這個實例可發送多附件 Filename: 
 * Mail.java 
 */  
public class Mail {  
  
    String to = "";// 收件人  
    String from = "";// 發件人  
    String host = "";// smtp主機  
    String username = "";  
    String password = "";  
    String filename = "";// 附件文件名  
    String subject = "";// 郵件主題  
    String content = "";// 郵件正文  
    @SuppressWarnings("unchecked")  
    Vector file = new Vector();// 附件文件集合  
  
    /** 
     *方法說明:默認構造器 輸入參數: 返回類型: 
     */  
    public Mail() {  
    }  
  
    /** 
     *方法說明:構造器,提供直接的參數傳入 輸入參數: 返回類型: 
     */  
    public Mail(String to, String from, String smtpServer, String username,  
            String password, String subject, String content) {  
        this.to = to;  
        this.from = from;  
        this.host = smtpServer;  
        this.username = username;  
        this.password = password;  
        this.subject = subject;  
        this.content = content;  
    }  
  
    /** 
     *方法說明:設置郵件服務器地址 輸入參數:String host 郵件服務器地址名稱 返回類型: 
     */  
    public void setHost(String host) {  
        this.host = host;  
    }  
  
    /** 
     *方法說明:設置登錄服務器校驗密碼 輸入參數: 返回類型: 
     */  
    public void setPassWord(String pwd) {  
        this.password = pwd;  
    }  
  
    /** 
     *方法說明:設置登錄服務器校驗用戶 輸入參數: 返回類型: 
     */  
    public void setUserName(String usn) {  
        this.username = usn;  
    }  
  
    /** 
     *方法說明:設置郵件發送目的郵箱 輸入參數: 返回類型: 
     */  
    public void setTo(String to) {  
        this.to = to;  
    }  
  
    /** 
     *方法說明:設置郵件發送源郵箱 輸入參數: 返回類型: 
     */  
    public void setFrom(String from) {  
        this.from = from;  
    }  
  
    /** 
     *方法說明:設置郵件主題 輸入參數: 返回類型: 
     */  
    public void setSubject(String subject) {  
        this.subject = subject;  
    }  
  
    /** 
     *方法說明:設置郵件內容 輸入參數: 返回類型: 
     */  
    public void setContent(String content) {  
        this.content = content;  
    }  
  
    /** 
     *方法說明:把主題轉換爲中文 輸入參數:String strText 返回類型: 
     */  
    public String transferChinese(String strText) {  
        try {  
            strText = MimeUtility.encodeText(new String(strText.getBytes(),  
                    "GB2312"), "GB2312", "B");  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return strText;  
    }  
  
    /** 
     *方法說明:往附件組合中添加附件 輸入參數: 返回類型: 
     */  
    public void attachfile(String fname) {  
        file.addElement(fname);  
    }  
  
    /** 
     *方法說明:發送郵件 輸入參數: 返回類型:boolean 成功爲true,反之爲false 
     */  
    public boolean sendMail() {  
  
        // 構造mail session  
        Properties props = System.getProperties();  
        props.put("mail.smtp.host", host);  
        props.put("mail.smtp.auth", "true");  
        Session session = Session.getDefaultInstance(props,  
                new Authenticator() {  
                    public PasswordAuthentication getPasswordAuthentication() {  
                        return new PasswordAuthentication(username, password);  
                    }  
                });  
  
        try {  
            // 構造MimeMessage 並設定基本的值  
            MimeMessage msg = new MimeMessage(session);  
            msg.setFrom(new InternetAddress(from));  
            InternetAddress[] address = { new InternetAddress(to) };  
            msg.setRecipients(Message.RecipientType.TO, address);  
            subject = transferChinese(subject);  
            msg.setSubject(subject);  
  
            // 構造Multipart  
            Multipart mp = new MimeMultipart();  
  
            // 向Multipart添加正文  
            MimeBodyPart mbpContent = new MimeBodyPart();  
            mbpContent.setText(content);  
            // 向MimeMessage添加(Multipart代表正文)  
            mp.addBodyPart(mbpContent);  
  
            // 向Multipart添加附件  
            Enumeration efile = file.elements();  
            while (efile.hasMoreElements()) {  
  
                MimeBodyPart mbpFile = new MimeBodyPart();  
                filename = efile.nextElement().toString();  
                FileDataSource fds = new FileDataSource(filename);  
                mbpFile.setDataHandler(new DataHandler(fds));  
                mbpFile.setFileName(fds.getName());  
                // 向MimeMessage添加(Multipart代表附件)  
                mp.addBodyPart(mbpFile);  
  
            }  
  
            file.removeAllElements();  
            // 向Multipart添加MimeMessage  
            msg.setContent(mp);  
            msg.setSentDate(new Date());  
            // 發送郵件  
            Transport.send(msg);  
  
        } catch (MessagingException mex) {  
            mex.printStackTrace();  
            Exception ex = null;  
            if ((ex = mex.getNextException()) != null) {  
                ex.printStackTrace();  
            }  
            return false;  
        }  
        return true;  
    }  
  
    /** 
     *方法說明:主方法,用於測試 輸入參數: 返回類型: 
     */  
    public static void main(String[] args) {  
        Mail sendmail = new Mail();  
        sendmail.setHost("smtp.sohu.com");  
        sendmail.setUserName("du_jiang");  
        sendmail.setPassWord("31415926");  
        sendmail.setTo("[email protected]");  
        sendmail.setFrom("[email protected]");  
        sendmail.setSubject("你好,這是測試!");  
        sendmail.setContent("你好這是一個帶多附件的測試!");  
        // Mail sendmail = new  
        // Mail("[email protected]","[email protected]","smtp.sohu.com","du_jiang","31415926","你好","胃,你好嗎?");  
        sendmail.attachfile("c:\\test.txt");  
        sendmail.attachfile("DND.jar");  
        sendmail.sendMail();  
  
    }  
}// end  

view plain
package test48;  
  
import javax.mail.*;  
import javax.mail.internet.*;  
import java.util.*;  
import java.io.*;  
/** 
 * Title: 使用JavaMail接收郵件 
 * Description: 實例JavaMail包接收郵件,本實例沒有實現接收郵件的附件。 
 * Filename: POPMail.java 
 */  
public class POPMail{  
/** 
 *方法說明:主方法,接收用戶輸入的郵箱服務器、用戶名和密碼 
 *輸入參數: 
 *返回類型: 
 */  
    public static void main(String args[]){  
        try{  
            String popServer=args[0];  
            String popUser=args[1];  
            String popPassword=args[2];  
            receive(popServer, popUser, popPassword);  
        }catch (Exception ex){  
            System.out.println("Usage: java com.lotontech.mail.POPMail"+" popServer popUser popPassword");  
        }  
        System.exit(0);  
    }   
/** 
 *方法說明:接收郵件信息 
 *輸入參數: 
 *返回類型: 
 */  
    public static void receive(String popServer, String popUser, String popPassword){  
        Store store=null;  
        Folder folder=null;  
        try{  
            //獲取默認會話  
            Properties props = System.getProperties();  
            Session session = Session.getDefaultInstance(props, null);  
            //使用POP3會話機制,連接服務器  
            store = session.getStore("pop3");  
            store.connect(popServer, popUser, popPassword);  
            //獲取默認文件夾  
            folder = store.getDefaultFolder();  
            if (folder == null) throw new Exception("No default folder");  
            //如果是收件箱  
            folder = folder.getFolder("INBOX");  
            if (folder == null) throw new Exception("No POP3 INBOX");  
            //使用只讀方式打開收件箱  
            folder.open(Folder.READ_ONLY);  
            //得到文件夾信息,獲取郵件列表  
            Message[] msgs = folder.getMessages();  
            for (int msgNum = 0; msgNum < msgs.length; msgNum++){  
                printMessage(msgs[msgNum]);  
            }  
        }catch (Exception ex){  
            ex.printStackTrace();  
        }  
        finally{  
        //釋放資源  
            try{  
                if (folder!=null) folder.close(false);  
                if (store!=null) store.close();  
            }catch (Exception ex2) {  
                ex2.printStackTrace();  
            }  
        }  
    }  
/** 
 *方法說明:打印郵件信息 
 *輸入參數:Message message 信息對象 
 *返回類型: 
 */  
    public static void printMessage(Message message){  
        try{  
            //獲得發送郵件地址  
            String from=((InternetAddress)message.getFrom()[0]).getPersonal();  
            if (from==null) from=((InternetAddress)message.getFrom()[0]).getAddress();  
            System.out.println("FROM: "+from);  
            //獲取主題  
            String subject=message.getSubject();  
            System.out.println("SUBJECT: "+subject);  
            //獲取信息對象  
            Part messagePart=message;  
            Object content=messagePart.getContent();  
            //附件  
            if (content instanceof Multipart){  
                messagePart=((Multipart)content).getBodyPart(0);  
                System.out.println("[ Multipart Message ]");  
            }  
            //獲取content類型  
            String contentType=messagePart.getContentType();  
            //如果郵件內容是純文本或者是HTML,那麼打印出信息  
            System.out.println("CONTENT:"+contentType);  
            if (contentType.startsWith("text/plain")||  
                contentType.startsWith("text/html")){  
                InputStream is = messagePart.getInputStream();  
                BufferedReader reader=new BufferedReader(new InputStreamReader(is));  
                String thisLine=reader.readLine();  
                while (thisLine!=null){  
                    System.out.println(thisLine);  
                    thisLine=reader.readLine();  
                }  
            }  
            System.out.println("-------------- END ---------------");  
        }catch (Exception ex){  
            ex.printStackTrace();  
        }  
    }  
}  

view plain
package test49;  
  
import java.io.*;  
import java.net.*;  
  
/** 
 * Title: 獲取一個URL文本 
 * Description: 通過使用URL類,構造一個輸入對象,並讀取其內容。 
 * Filename: getURL.java 
 */  
public class getURL{  
  
 public static void main(String[] arg){  
  if(arg.length!=1){  
    System.out.println("USE java getURL  url");  
    return;  
  }  
  new getURL(arg[0]);  
 }  
/** 
 *方法說明:構造器 
 *輸入參數:String URL 互聯網的網頁地址。 
 *返回類型: 
 */  
 public getURL(String URL){  
    try {  
        //創建一個URL對象  
        URL url = new URL(URL);  
      
        //讀取從服務器返回的所有文本  
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));  
        String str;  
        while ((str = in.readLine()) != null) {  
            //這裏對文本出來  
            display(str);  
        }  
        in.close();  
    } catch (MalformedURLException e) {  
    } catch (IOException e) {  
    }  
 }  
/** 
 *方法說明:顯示信息 
 *輸入參數: 
 *返回類型: 
 */  
 private void display(String s){  
   if(s!=null)  
     System.out.println(s);  
 }  
}  

view plain
package test50;  
import java.io.*;  
  
/** 
 * Title: 客戶請求分析 
 * Description: 獲取客戶的HTTP請求,分析客戶所需要的文件 
 * Filename: Request.java 
 */  
public class Request{  
  InputStream in = null;  
/** 
 *方法說明:構造器,獲得輸入流。這時客戶的請求數據。 
 *輸入參數: 
 *返回類型: 
 */  
  public Request(InputStream input){  
    this.in = input;  
  }  
/** 
 *方法說明:解析客戶的請求 
 *輸入參數: 
 *返回類型:String 請求文件字符 
 */  
  public String parse() {  
    //從Socket讀取一組數據  
    StringBuffer requestStr = new StringBuffer(2048);  
    int i;  
    byte[] buffer = new byte[2048];  
    try {  
        i = in.read(buffer);  
    }  
    catch (IOException e) {  
        e.printStackTrace();  
        i = -1;  
    }  
    for (int j=0; j<i; j++) {  
        requestStr.append((char) buffer[j]);  
    }  
    System.out.print(requestStr.toString());  
    return getUri(requestStr.toString());  
  }  
/** 
 *方法說明:獲取URI字符 
 *輸入參數:String requestString 請求字符 
 *返回類型:String URI信息字符 
 */  
  private String getUri(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;  
  }  
}  

view plain
package test50;  
import java.io.*;  
  
/** 
 * Title: 發現HTTP內容和文件內容 
 * Description: 獲得用戶請求後將用戶需要的文件讀出,添加上HTTP應答頭。發送給客戶端。 
 * Filename: Response.java 
 */  
public class Response{  
  OutputStream out = null;  
/** 
 *方法說明:發送信息 
 *輸入參數:String ref 請求的文件名 
 *返回類型: 
 */  
  @SuppressWarnings("deprecation")  
public void Send(String ref) throws IOException {  
    byte[] bytes = new byte[2048];  
    FileInputStream fis = null;  
    try {  
        //構造文件  
        File file  = new File(WebServer.WEBROOT, ref);  
        if (file.exists()) {  
            //構造輸入文件流  
            fis = new FileInputStream(file);  
            int ch = fis.read(bytes, 0, 2048);  
            //讀取文件  
            String sBody = new String(bytes,0);  
            //構造輸出信息  
            String sendMessage = "HTTP/1.1 200 OK\r\n" +  
                "Content-Type: text/html\r\n" +  
                "Content-Length: "+ch+"\r\n" +  
                "\r\n" +sBody;  
            //輸出文件  
            out.write(sendMessage.getBytes());  
        }else {  
            // 找不到文件  
            String errorMessage = "HTTP/1.1 404 File Not Found\r\n" +  
                "Content-Type: text/html\r\n" +  
                "Content-Length: 23\r\n" +  
                "\r\n" +  
                "<h1>File Not Found</h1>";  
            out.write(errorMessage.getBytes());  
        }  
         
    }  
    catch (Exception e) {  
        // 如不能實例化File對象,拋出異常。  
        System.out.println(e.toString() );  
    }  
    finally {  
        if (fis != null)  
            fis.close();  
    }  
 }  
/** 
 *方法說明:構造器,獲取輸出流 
 *輸入參數: 
 *返回類型: 
 */  
 public Response(OutputStream output) {  
    this.out = output;  
}  
}  

view plain
package test50;  
  
import java.io.*;  
import java.net.*;  
  
/** 
 * Title: WEB服務器 
 * Description: 使用Socket創建一個WEB服務器,本程序是多線程系統以提高反應速度。 
 * Filename: WebServer.java 
 */  
class WebServer  
{  
 public static String WEBROOT = "";//默認目錄  
 public static String defaultPage = "index.htm";//默認文件  
 public static void main (String [] args) throws IOException  
 {//使用輸入的方式通知服務默認目錄位置,可用./root表示。  
   if(args.length!=1){  
     System.out.println("USE: java WebServer ./rootdir");  
     return;  
   }else{  
     WEBROOT = args[0];  
   }  
   System.out.println ("Server starting...\n");   
   //使用8000端口提供服務  
   ServerSocket server = new ServerSocket (8000);  
   while (true)  
   {  
    //阻塞,直到有客戶連接  
     Socket sk = server.accept ();  
     System.out.println ("Accepting Connection...\n");  
     //啓動服務線程  
     new WebThread (sk).start ();  
   }  
 }  
}  
  
/** 
 * Title: 服務子線程 
 * Description: 使用線程,爲多個客戶端服務 
 
 * Filename:  
 
 
 */  
class WebThread extends Thread  
{  
 private Socket sk;  
 WebThread (Socket sk)  
 {  
  this.sk = sk;  
 }  
/** 
 *方法說明:線程體 
 *輸入參數: 
 *返回類型: 
 */  
 public void run ()  
 {  
  InputStream in = null;  
  OutputStream out = null;  
  try{  
    in = sk.getInputStream();  
    out = sk.getOutputStream();  
      //接收來自客戶端的請求。  
      Request rq = new Request(in);  
      //解析客戶請求  
      String sURL = rq.parse();  
      System.out.println("sURL="+sURL);  
      if(sURL.equals("/")) sURL = WebServer.defaultPage;  
      Response rp = new Response(out);  
      rp.Send(sURL);        
    }catch (IOException e)  
    {  
       System.out.println (e.toString ());  
    }  
    finally  
    {  
      System.out.println ("Closing Connection...\n");  
      //最後釋放資源  
      try{  
       if (in != null)  
         in.close ();  
       if (out != null)  
         out.close ();  
        if (sk != null)  
          sk.close ();  
      }  
      catch (IOException e)  
      {  
      }  
    }  
 }  
}  

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章